简体   繁体   中英

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 '

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. 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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