Forum Moderators: coopster

Message Too Old, No Replies

array issues with intersect

         

PHPycho

5:48 am on Jan 14, 2010 (gmt 0)

10+ Year Member



Problem: see the inline comments in the following code:
[PHP]<?php
$array1 = array(
'key1' => array(
'name' => 'Product1.1'
,'price' => 220
,'qty_in_x' => 100
)
,'key2' => array(
'name' => 'Product1.2'
,'price' => 120
,'qty_in_x' => 150
)
/* and so on... */
);

$array2 = array(
'key11' => array(
'name' => 'Product2.1'
,'price' => 50
,'qty_in_y' => 150
)
,'key2' => array(
'name' => 'Product2.2'
,'price' => 80
,'qty_in_y' => 180
)
/* and so on... */
);

//what i want to do is intersect the two arrays by keys and want to get the results as:
$final_array = array(
'key2' => array(
'name' => 'Product1.2'
,'price' => 120
,'qty_in_x' => 150
,'qty_in_y' => 180 //Note: this should be merged from $array2
)
);

//I tried with:
$final_array = array_intersect_key($array1, $array2);
print_r($final_array);
/*Which Results:
Array
(
[key2] => Array
(
[name] => Product1.2
[price] => 120
[qty_in_x] => 150
)

)
which just gave the fields from $array1 excluding 'qty_in_y'
*/
?>[/PHP]
Is there any way to accomplish as mentioned above?
Thanks

andrewsmd

3:18 pm on Jan 14, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try this
$array1 = array(
'key1' => array(
'name' => 'Product1.1'
,'price' => 220
,'qty_in_x' => 100
)
,'key2' => array(
'name' => 'Product1.2'
,'price' => 120
,'qty_in_x' => 150
)
/* and so on... */
);
$array2 = array(
'key1' => array(
'name' => 'Product2.1'
,'price' => 50
,'qty_in_y' => 150
)
,'key2' => array(
'name' => 'Product2.2'
,'price' => 80
,'qty_in_y' => 180
)
/* and so on... */
);

//the final array
$finalArray = array();

foreach($array1 as $key=>$i){

$tempName = $i["name"];
$tempPrice = $i["price"];
$tempX = $i["qty_in_x"];

//now go through the second array and see if we can find the key
foreach($array2 as $secondKey=>$secondValue){

//if the keys match
if($key == $secondKey){

$finalArray[$key] = array("name" => $tempName, "price" => $tempPrice, "qty_in_x" => $tempX, "qty_in_y" => $secondValue["qty_in_y"]);

}//if

}//foreach array2

}//foreach

print_r($finalArray);

Just note, there are a few things I could do to make this more efficient. I did it through for loops to try to break it down. If you are dealing with large arrays, let me know and I can speed it up for you.