如何从多阵列中获取价值?

时间:2017-12-06 21:06:41

标签: php

如果条件匹配,我想从多数组中获取变量的特定值。

当我打印我的数组时:

print_r($myarray);

给出如下数组:

Array
(
  [0] => Array
   (
     [id] => 21 //check for this value
     [customer_id] => 12456 //get this value 
     [date] => 12-06-2017         
   )
  [1] => Array
   (
     [id] => 15
     [customer_id] => 12541 
     [date] => 12-06-2017
   )
  [2] => Array
   (
     [id] => 12
     [customer_id] => 25415
     [date] => 12-06-2017
   )
)

如果 ID 21 相匹配

,我试图获得客户编号
foreach ($myarray as $array){
  if($array[][id] == "21"){ //this is where I'm making mistake
    $cust_id = $myarray[]['customer_id'];
    return $cust_id;
  }
}

3 个答案:

答案 0 :(得分:4)

由于您通过数组 循环,因此您已经拥有单项。所以就这样做吧

foreach ($myarray as $array) {
  if ($array["id"] == "21") {
    return $array["customer_id"];
  }
}

答案 1 :(得分:0)

你可以创建一个自定义函数并调用它,就像这样

function arraySearch($theArray, $searchKey, $searchValue, $returnKey){

    foreach($theArray as $value){
            if($value[$searchKey] == $searchValue)  return $value[$returnKey]; //found, return the value of the choosen $returnKey var
    }

     return false; //not found, so return false

}

然后使用它

echo arraySearch($myarray, 'id', '21', 'customer_id'); // it returns 12456

EXAMPLE

答案 2 :(得分:0)

foreach ($myarray as $array){
  if($array["id"] == 21){
    $cust_id = $array['customer_id'];
    return $cust_id;
  }
}
相关问题