0

I would like create a list of values within a new array based on the same keys from the previous array. Basically, I would like to turn this array:

$old_array = Array (
  [segment1] => Array (
     [subsegment] => Array (
        [number1] => 1413
        [number2] => 306
     )
   )
  [segment2] => Array (
     [subsegment] => Array (
        [number1] => 717
        [number2] => 291
     )
   )
 )

...into this array:

$new_array = Array (
  [segment] => Array (
     [subsegment] => Array (
        [number1] => Array (
           [0] => 1413
           [1] => 717
        )
        [number2] => Array (
           [0] => 306
           [1] => 291
        )
     )
   )
 )

I tried the following:

$new_array = array ();
foreach ($old_array["segment"]["subsegment"] as $value) {
   $new_array["segment"]["subsegment"][] = $value;
}

Unfortunately, this doesn't work. What do I need to do? Thanks.

TheBigDoubleA
  • 432
  • 2
  • 7
  • 26
  • thanks for the downvote Christopher... I've tried so many different things and have spent hours trying to figure this thing out... Do you really think it's necessary to list up everything I've tried? – TheBigDoubleA Jan 20 '14 at 16:32
  • 1
    i didn't downvote :-) but yeah you need to show at least one thing you tried. – cmorrissey Jan 20 '14 at 16:34
  • Thanks for not bothering to comment jeroen. I've updated my post, Christopher. Let me know if I need to add anything. Thanks for your help. – TheBigDoubleA Jan 20 '14 at 16:46
  • 1
    Your `$old_array` does not seem valid. How can you have the same `segment` key in the `$old_array` twice? Can you show us actual `var_dump()` of `$old_array`? – Mike Brant Jan 20 '14 at 16:48
  • yes you need provide a valid array – Emilio Gort Jan 20 '14 at 16:58
  • Mike, so sorry about this. I forgot to add the numbers to the "segment" - have updated it now and it should be valid. – TheBigDoubleA Jan 20 '14 at 16:58

2 Answers2

1

I understand you want all number1's in the same key, then all number 2's, and so on. try this:

$numberCount = count($old_array['segment1']['subsegment']);
foreach ($old_array as $segment)
 {for ($i=1;$i<=$numberCount;$i++)
   {$new_array['segment']['subsegment']['number' . $i][] = $segment['subsegment']['number' . $i];}}

this is assuming all subsegment have the same number of [numberx] keys

1

This is very specific to your example $old_array:

$index = 1;
$new_array = array();
do {
    if (!isset($old_array["segment" . $index]["subsegment"]))
        break;
    foreach ($old_array["segment" . $index]["subsegment"] as $key => $value) {
        $new_array["segment"]["subsegment"][$key][] = $value;
    }
    $index++;
} while (true);
Mark Ormston
  • 1,836
  • 9
  • 13