Reputation: 3
I have two array with multiple key and values, but i want final array comparing first array key and value if that value occured in second array then it will return else unset all index array values.
my first array
Array
(
[0] => Array
(
[TXNID] => 225
)
[1] => Array
(
[TXNID] => 226
)
)
second array:
Array
(
[0] => Array
(
[TXNID] => 224
[TransactionName] => PAY-15-16-0031
[TransactionDate] => 2015-05-12 00:00:00
)
[1] => Array
(
[TXNID] => 225
[TransactionName] => RCT-15-16-0096
[TransactionDate] => 2015-05-13 00:00:00
)
[2] => Array
(
[TXNID] => 226
[TransactionName] => PAY-15-16-0032
[TransactionDate] => 2015-05-13 00:00:00
)
)
Final array:
Array
(
[0] => Array
(
[TXNID] => 225
[TransactionName] => RCT-15-16-0096
[TransactionDate] => 2015-05-13 00:00:00
)
[1] => Array
(
[TXNID] => 226
[TransactionName] => PAY-15-16-0032
[TransactionDate] => 2015-05-13 00:00:00
)
)
Upvotes: 0
Views: 74
Reputation: 1104
I have considered simple example to explain the workings,
please refer below.
$keys = array(
"field1" => "first",
"field2" => "second",
"field3" => "third"
);
$values = array(
"field1value" => "dinosaur",
"field2value" => "pig",
"field3value" => "platypus"
);
foreach ($keys as $arrval1) {
$newarray1[$arrval1] = $arrval1;
}
$i = 0;
foreach ($values as $arrval2) {
$j = 0;
foreach ($newarray1 as $key => $val) {
if ($i == $j) {
$newarray1[$key] = $arrval2;
break;
}
$j++;
}
$i++;
}
print_r($newarray1);
Upvotes: 0
Reputation: 6253
//array1 is the first array you gave
//array2 the second
//array3 the result
function array_key_exists_r($needle, $haystack)
{
$result = array_key_exists($needle, $haystack);
if ($result) return $result;
foreach ($haystack as $v) {
if (is_array($v)) {
$result = array_key_exists_r($needle, $v);
}
if ($result) return $result;
}
return $result;
}
foreach($array2 as $elem_array2)
{
if(array_key_exists_r($elem_array2['TXNID'],$array1))
$array3[] = $elem_array2;
}
Upvotes: 1
Reputation: 3427
This will get the job done, but having two nested loops is not good
$output = array();
foreach ($first as $f) {
foreach ($second as $s) {
if ($s['TXNID'] == $f['TXNID']) {
$output[] = $s;
}
}
}
It would be better to reorganize the input beforehand:
$first = array(
225,
226
);
$second = array(
224 => array(
'TransactionName' => 'PAY-15-16-0031',
'TransactionDate' => '2015-05-12 00:00:00'
),
225 => array(
'TransactionName' => 'RCT-15-16-0096',
'TransactionDate' => '2015-05-13 00:00:00'
),
226 => array(
'TransactionName' => 'PAY-15-16-0032',
'TransactionDate' => '2015-05-13 00:00:00'
)
);
Then you can iterate over $first
and directly use each value as a key into $second
without needing a third array.
foreach ($first as $key) {
// do something with $second[$key]
}
Upvotes: 1