开发者

duplicate one element from php array

how i can duplicate one element from array:

for example, i have this array:

Array
(
    [LRDEPN] => 0008.jpg
    [OABCFT] => 0030.jpg
    [SIFCFJ] => 0011.jpg
    [KEMOMD] => 0022.jpg
    [DHORLN] => 0026.jpg
    [AHFUFB] => 0029.jpg
)

if i want to duplicate this: 0011.jpg , how to proceed?

i want to get this:

Array
(
    [LRDEPN] => 0008.jpg
    [OABCFT] =>开发者_如何学JAVA 0030.jpg
    [SIFCFJ] => 0011.jpg
    [NEWKEY] => 0011.jpg
    [KEMOMD] => 0022.jpg
    [DHORLN] => 0026.jpg
    [AHFUFB] => 0029.jpg
)


Something like the following, change the uniqid() function to yours:

<?php

$a=array(
    'LRDEPN' => '0008.jpg',
    'OABCFT' => '0030.jpg',
    'SIFCFJ' => '0011.jpg',
    'KEMOMD' => '0022.jpg',
    'DHORLN' => '0026.jpg',
    'AHFUFB' => '0029.jpg'
);

$i='0011.jpg';

$newArray=array();
foreach($a as $k=>$v){
    $newArray[$k]=$v;
    if($v==$i) $newArray[uniqid()]=$v;
}

print_r($newArray);

?>

Which gets you:

Array
(
    [LRDEPN] => 0008.jpg
    [OABCFT] => 0030.jpg
    [SIFCFJ] => 0011.jpg
    [4bd014ebf3351] => 0011.jpg
    [KEMOMD] => 0022.jpg
    [DHORLN] => 0026.jpg
    [AHFUFB] => 0029.jpg
)


EDIT:

Looks like you modified your question :)

If you want to have a new key with the duplicated value you can do:

$array_name['NEWKEY'] = $array_name['SIFCFJ']

Old answer:

You cannot.

An array cannot have multiple values with same key.

$arr = array();
$arr['foo'] = 'bar1';
$arr['foo'] = 'bar2'; // this will wipe out bar1

And if you try to duplicate:

$arr = array();
$arr['foo'] = 'bar1';
$arr['foo'] = 'bar1';

you'll be overwriting the value bar1 associated with key foo with bar1 itself. The array will have 1 key value pair not 2.


$arr['newkey'] = $arr['oldkey'];
natsort($arr);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜