Jump to content

help with merging arrays


blackhawk

Recommended Posts

Hello I have read documents online to merge and transform arrays but I am stuck on logic to take an array that looks like this....

 

Array
(
    [0] => Array
        (
          [one] => 2
          [two] => 9820
          [three] => 4
          [four] => 39338
        )

[1] => Array
        (
          [one] => 3
          [two] => 9832
          [three] => 4
          [four] => cat
        )
[2] => Array
        (
          [one] => Hello
          [two] => 9282
          [three] => 3
          [four] => dog
        )
)

 

...and combine the sub arrays where key value [three]  is found in another sub array with the same value! - the above example shows that [three] => 4 has identical matches in [0] => array and [1] => array.  Is it possible to merge these 2 sub arrays due to this fact? and let the rest of the sub arrays be added on as normal? something like this...

 

Array
(
    [0] => Array
          [one] => 2
          [two] => 9820
          [three] => 4
          [four] => 39338
          [one] => Hello
          [two] => 9282
          [three] => 3
          [four]=> dog
)

[1] => Array
        (
          [one] => 3
          [two] => 9832
          [three] => 4
          [four] => cat
        )
)

 

I know that i need unique keys but i really want my keys to be the same no matter how deep my sub arrays are.  Any suggestions?

 

thanks!

 

Link to comment
https://forums.phpfreaks.com/topic/185621-help-with-merging-arrays/
Share on other sites

solved!

you can use this function...

 

function array_collapse($arr, $x, $y) {
    $carr = array();
    while ($el = current($arr)) {
        $carr[ $el[$x] ] = $el[$y];
        next($arr);
    }
    return $carr;
}

 

or this one

 

function seekKey($array, $key, $value)
{
    $ret = array();
    for ($i=0;$i<count($array);$i++)
    {
        if ($array[$i][$key]==$value)
            $ret[] = $array[$i];
    }
    return $ret;
}

to get the key value pair that you need to focus on! from there its easy to take different parts of the sub array apart and rebuild them!

 

:D

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.