简体   繁体   English

PHP的多维数组的关键和获得价值

[英]php Multidimensional Array for key and get value

I have the following code sample: 我有以下代码示例:

$arr = array(
  array(
    'packid'=> '1', 'total' => '30'),
  array(
    'packid'=> '2', 'total' => '20')
);

$arr is in a loop $ arr处于循环中

 foreach ($pack->memberPack as $memPack) {
            if($memPack->packId = $search_arr_key)
            //get the `total` value then do something
        }

and $memPack object like this: 和$ memPack对象是这样的:

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? 如何搜索的关键packId等于$memPack->packId并拿到赛总? (ex. if packId =2 and get the value 20 ) (例如,如果packId =2并获得值20)

I think you are looking for a loop that finds the result according to the packid you select. 我认为您正在寻找一个循环,该循环根据您选择的packid查找结果。

<?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. 只需简单地迭代数组并检查子数组是否包含匹配的packidtotal项。 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_column按照与$arr packid数组的顺序匹配的顺序,从packid值( [1, 2] )构建一个数组; 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 ). array_search返回packid值数组中第一个出现的$packid的索引(因此,返回$arr packid数组的键)。 The rest of the code fetches the total . 其余代码将获取total

I have added this example for completeness. 为了完整性,我添加了此示例。 Don't use it as it is suboptimal. 不要使用它,因为它不是最佳的。

For better performance, here is a good implementation. 为了获得更好的性能,这是一个很好的实现。

$array = array_combine(array_column($arr, 'packId'), array_column($arr, 'total'));
$total = $array[$memPack->packId];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM