使用value从数组数组中获取数组

时间:2017-10-19 05:26:19

标签: php arrays

我有一个像这样的数组

$data=array(
      array("9900","1","7"),
      array("9901","1","7"),
      array("9902","1","7"),
      array("9903","1","4"),
      array("9904","3","8"),
      array("9908","1","5")
);

我有价值9908。当我搜索9908时,应打印值array("9908","1","5")。我使用过array_search(),但我没有取得任何成功

如何在找到值

后打印数组

4 个答案:

答案 0 :(得分:2)

试试这个:

var_dump($data[array_search("9908", array_column($data, 0))]);

要扩展它,

  

array_column返回输入的单个列中的值,由column_key标识。 (可选)可以提供index_key,以通过输入数组的index_key列中的值索引返回数组中的值。

  

array_search在数组中搜索给定值,如果成功则返回第一个相应的键。

修改

添加一些控制权:

$index = array_search("9908", array_column($data, 0));
if($index !== false){
    // do your stuff with $data[$index];
    var_dump($data[$index]);
}

转储:

array(3) {
  [0]=>
  string(4) "9908"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "5"
}

答案 1 :(得分:1)

也许这会有所帮助:

<?php
function search_first_row($needle, $haystack){
  $data = $haystack;
  $desired_value = $needle;
  foreach($data as $row){
    if($row[0] == $desired_value){
        return $row;
    }
  }
}

答案 2 :(得分:0)

 $data=array(
    array("9900","1","7"),
    array("9901","1","7"),
    array("9902","1","7"),
    array("9903","1","4"),
    array("9904","3","8"),
    array("9908","1","5")
);
$searchValue = '9908';

for($i=0; $i<count($data); $i++){
    $innerArray = $data[$i];

    for($j=0; $j<count($innerArray); $j++){
        if($innerArray[$j] == $searchValue){
            print_r($innerArray);
        }
    }
}

答案 3 :(得分:0)

试试这个:

    $data=array(
      array("9900","1","7"),
      array("9901","1","7"),
      array("9902","1","7"),
      array("9903","1","4"),
      array("9904","3","8"),
      array("9908","1","5")
);
foreach ($data as $key => $value) {

    if( in_array("9908",$value)){
        $findindex = $key;
}
}
var_dump($data[$findindex]);