I have the following code sample:
$arr = array(
array(
'packid'=> '1', 'total' => '30'),
array(
'packid'=> '2', 'total' => '20')
);
$arr is in a loop
foreach ($pack->memberPack as $memPack) {
if($memPack->packId = $search_arr_key)
//get the `total` value then do something
}
and $memPack object like this:
array(1) {
["memberPack"]=>
array(1) {
[0]=>
object(MemberPack)#290 (6) {
["errors"]=>
NULL
["attributes":"ActiveRecord\Model":private]=>
array(3) {
["memberPackId"]=>
int(1)
["packId"]=>
int(1)
["memberId"]=>
int(14369)
}
}
}
}
How can i search the key packId
equal to $memPack->packId
and get the match total? (ex. if packId =2
and get the value 20 )
For better performance, here is a good implementation.
$array = array_combine(array_column($arr, 'packId'), array_column($arr, 'total'));
$total = $array[$memPack->packId];
I think you are looking for a loop that finds the result according to the packid you select.
<?php
$arr = array(
array(
'packid'=> '1', 'total' => '30'),
array(
'packid'=> '2', 'total' => '20')
);
$whateverPackidYouWant = 2;
$answer;
for ($i = 0; $i < count($arr); $i++) {
if ($arr[$i]['packid'] == $whateverPackidYouWant) {
$answer = $arr[$i]['total'];
}
}
echo $answer;
?>
Please let me know if this is what you were looking for.
Simply iterate the array and check if the subarray contains the matching packid
and total
items. Break the loop on the first match:
$packid = 2;
foreach ($arr as $k => $v) {
if ($v['packid'] == $packid && isset($v['total'])) {
$total = $v['total'];
break;
}
}
Another approach (less optimal, but may look elegant to some people):
$key = array_search($packid, array_column($arr, 'packid'));
if ($key !== false && isset($arr[$key]['total'])) {
$total = $arr[$key]['total'];
}
where array_column
builds an array from the packid
values ([1, 2]
) in the order that matches the order of subarrays in $arr
; array_search
returns the index of the first occurrence of $packid
in the array of packid
values (and thus, the key of the subarray in $arr
). The rest of the code fetches the total
.
I have added this example for completeness. Don't use it as it is suboptimal.