Jump to content

[SOLVED] PHP Array manipulation with recursion?


neewom

Recommended Posts

I think this will require recursion, but here goes:

 

I have code that generates some arrays for me and I need to know how to manipulate this data so I can use it.

 

This is what I have:

 

$arr1 = Array(1900 => 140, 1905 => 140, 1919 => 140, 1920 => 140);

$arr2 = Array(1900 => 1040, 1905 => 3563, 1919 => 5776, 1920 => 4903);

$arr3 = Array(1900 => 7764, 1905 => 90713, 1919 => 238328, 1920 => 171713);

 

I Want this:

 

$newArr1 = Array(1900, 140, 1040, 7764); // All values for 1900 from $arr1, $arr2, and $arr3.

$newArr2 = Array(1905, 140, 3563, 90713); // All values for 1905 from $arr1, $arr2, and $arr3.

$newArr3 = Array(1919, 140, 5776, 238328); // All values for 1919 from $arr1, $arr2, and $arr3.

$newArr4 = Array(1920, 140, 4903, 171713); // All values for 1920 from $arr1, $arr2, and $arr3.

 

its all the same data just all the values of each key are in one array instead of different ones.

 

try

$arr1 = Array(1900 => 140, 1905 => 140, 1919 => 140, 1920 => 140);
$arr2 = Array(1900 => 1040, 1905 => 3563, 1919 => 5776, 1920 => 4903);
$arr3 = Array(1900 => 7764, 1905 => 90713, 1919 => 238328, 1920 => 171713);

$newArr = array();
foreach ($arr1 as $k => $v) $newArr[$k][] = $v;
foreach ($arr2 as $k => $v) $newArr[$k][] = $v;
foreach ($arr3 as $k => $v) $newArr[$k][] = $v;

echo '<pre>', print_r($newArr, true), '</pre>';

 

-->

Array
(
    [1900] => Array
        (
            [0] => 140
            [1] => 1040
            [2] => 7764
        )

    [1905] => Array
        (
            [0] => 140
            [1] => 3563
            [2] => 90713
        )

    [1919] => Array
        (
            [0] => 140
            [1] => 5776
            [2] => 238328
        )

    [1920] => Array
        (
            [0] => 140
            [1] => 4903
            [2] => 171713
        )

)

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.