简体   繁体   English

搜索值多维数组

[英]search for value multidimensional array

My array: 我的数组:

 Array ([friends] => Array ( [data] => Array ( 
    [0] => Array ( [id] => 1000001823093 [gender] => female [name] => Iri Ghi ) 
    [1] => Array ( [id] => 1000002320316 [gender] => female [name] => Nicole Torn ) 
    [2] => Array ( [id] => 1000003536987 [gender] => female [name] => An Bula ) 
    [3] => Array ( [id] => 1000005923120 [gender] => male [name] => Valent Acc ) 
    [4] => Array ( [id] => 1000008308250 [gender] => female [name] => Dia Apost) 
    [5] => Array ( [id] => 1000008685765 [gender] => female [name] => Mon Nicole )
    )))

We value 'id: 1000001823093 'and I need to search in the array and print' name: Iri Ghi ' 我们重视'id:1000001823093',我需要在数组中搜索并打印'name:Iri Ghi'

There are two ways to do this Choose the one that you like 有两种方法可以执行此操作选择您喜欢的一种

Method one: 方法一:

$find = 1000001823093;
for($i = 0; $i < count($array['friend']['data']); $i++) {
    if($array['friend']['data'][$i]['id'] == $find) 
        echo $array['friend']['data'][$i]['name'];
}

Method two: 方法二:

$find = 1000001823093;
foreach($array['friend']['data'] as $data) {
    if($data['id'] == $find)
        echo $data['name'];
}

Something like this: 像这样:

function findByID($data, $id) {

  $found = "";

  foreach($data['friends']['data'] as $friend) {

    if ($friend['id'] == $id) {
      $found = $friend['name'];
      break;
    } 
  }

  return $found;
}

$name = findByID($your_data_array, "1000001823093");

You can do it with php 's own FilterIterator, if you are working in a more oop way. 如果您使用的是更多工作方式,则可以使用php自己的FilterIterator进行操作。 Simple example: 简单的例子:

class MyFilterIterator extends FilterIterator {
    protected $idFilter = 0;

    public function __construct(Iterator $iterator, $idFilter) {
        parent::__construct($iterator);
        $this->idFilter = $idFilter;
    }

    public function accept() {
        $current = $this->getInnerIterator()->current();
        if ($current['id'] == $this->idFilter) {
            return true;
        }

        return false;
    }
}

$data = [
    ['id' => 1, 'value' => 'bla'],
    ['id' => 2, 'value' => 'blubb'],
];

$iterator = new ArrayIterator($data);
$filter = new MyFilterIterator($iterator, 2);

foreach ($filter as $item) {
    var_dump($item); // outputs the array with id 2
}

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

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