搜索值多维数组

时间:2014-03-16 10:59:30

标签: php arrays multidimensional-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 )
    )))

我们重视' id:1000001823093'我需要在数组中搜索并打印'姓名:Iri Ghi'

3 个答案:

答案 0 :(得分:1)

有两种方法可以做到这一点 选择你喜欢的那个

方法一:

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

方法二:

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

答案 1 :(得分:0)

这样的事情:

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");

答案 2 :(得分:0)

如果你的工作方式更加流行,你可以使用php自己的FilterIterator。简单的例子:

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
}