mark rammmy
mark rammmy

Reputation: 1498

php filter array values based on key

I have two arrays: $arr1 and $arr2. The two arrays have equal keys. I am merging the two arrays with duplicate keys. My output should show the duplicate keys with their corresponding values, for example

the key 22 exists and contains values 333,673,434 

Below is my current code:

<?
    $result = array();
    foreach ($arr1 as $i => $key) 
    {
        $result[] = array($key => $arr2[$i]);
    }

    print_r($result);
?>

Result as below

Array
(
    [0] => Array
        (
            [22] => 333
        )

    [1] => Array
        (
            [22] => 673
        )

    [2] => Array
        (
            [22] => 434
        )

    [3] => Array
        (
            [29] => 67
        )?>

    [4] => Array
        (
            [29] => 98
        )
[5] => Array
        (
            [29] => 656
        )

    [6] => Array
        (
            [28] => 12
        )
}

Upvotes: 0

Views: 389

Answers (1)

hsuk
hsuk

Reputation: 6860

Change:

 $result[] = array($key => $arr2[$i]);

To

 $result[$key][] = $arr2[$i];

You should get a array for each index. i.e. for 22, 28 and 29.

On 22, you should get a array containing 333,673 and 434.

If you need that value on comma separated value, then, try

if(is_array($result)&&!empty($result))
    foreach($result as $key => $item)
        $result_new[$key] = implode(',', $result[$key]);
print_r($result_new);

Upvotes: 1

Related Questions