开发者

php re-create an array to new keys and values

I have the following array of keys and values. How can i rec开发者_运维技巧reate this array to make the second column as the key and 3rd column the values. Also remove all unwanted spacings.

Array
(
    [16] =>     hasKeyframes    : true
    [17] =>     hasMetadata     : true
    [18] =>     duration        : 30
    [19] =>     audiosamplerate : 22000
    [20] =>     audiodatarate   : 68
    [21] =>     datasize        : 1103197
}

New array should look like this.

Array
(
    [hasKeyframes] => true
    [hasMetadata] => true
    ...
}


$newArray=array();
foreach($array as $value)
{
  $pair=explode(":",$value);
  $newArray[trim($pair[0])] = trim($pair[1]);
}

EDIT

if we have something like [19] => Duration: 00:00:31.03, then we only get 00 for $pair[1]

$newArray=array();
foreach($array as $value)
{
  $pair=explode(":",$value,2);
  $newArray[trim($pair[0])] = trim($pair[1]);
}


My solution uses array_walk() and works from PHP 5.3 because of the anonymous function used.

$array=array(/* ORIGINAL ARRAY */);
$newarray=array();

array_walk($array, function ($v, $k) use (&$newarray) {
    $pos=strpos($v, ':');
    $newkey=substr($v, 0, $pos);
    $newvalue=substr($v, $pos+1);
    $newarray[$newkey]=$newvalue;
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜