1

I have the following array of keys and values. How can i recreate 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
    ...
}
4
  • just loop and assign new keys and values to a new array Commented Jun 8, 2011 at 8:00
  • How are you storing the key and values at the moment? Are they in two separate arrays? Can you provide the actual PHP code? Commented Jun 8, 2011 at 8:03
  • @Cold Hawaiian it's the output of ffmpeg if I remember correctly Commented Jun 8, 2011 at 8:06
  • yes thank you @carlos. I wish people would answer the question rather then ask why the array looks like this. Commented Jun 8, 2011 at 8:13

2 Answers 2

4
$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]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @shakti, this works, but what if we have something like [19] => Duration: 00:00:31.03, then we only get 00 for $pair[1]
@Pinkie use third parameter of explode function rather than adding a space in explode: $pair = explode(":", $value, 2);
@Carlos: True, I was editing my answer for the same when you commented.
Yes, great one @carlos. I'll make use of that.
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;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.