在嵌套数组中搜索值 [英] Search for values in nested array

查看:121
本文介绍了在嵌套数组中搜索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下数组

array(2) {
  ["operator"] => array(2) {
    ["qty"] => int(2)
    ["id"] => int(251)
  }
  ["accessory209"] => array(2) {
    ["qty"] => int(1)
    ["id"] => int(209)
  }
  ["accessory211"] => array(2) {
    ["qty"] => int(1)
    ["id"] => int(211)
  }
}

我试图找到一种方法来验证数组中是否存在id值并返回bool.我试图找出一种不需要创建循环的快速方法.使用in_array函数无效,而且我还读到它非常慢.

I'm trying to find a way to verify an id value exists within the array and return bool. I'm trying to figure out a quick way that doesn't require creating a loop. Using the in_array function did not work, and I also read that it is quite slow.

在php手册中,有人建议先使用flip_array()然后再使用isset(),但我无法使它适用于二维数组.

In the php manual someone recommended using flip_array() and then isset(), but I can't get it to work for a 2-d array.

做类似的事情

if($array['accessory']['id'] == 211)

也可以为我工作,但是我需要匹配所有包含附件的钥匙-不知道该怎么做

would also work for me, but I need to match all keys containing accessory -- not sure how to do that

无论如何,我在圈子中旋转,可以使用一些帮助. 这似乎应该很容易.谢谢.

Anyways, I'm spinning in circles, and could use some help. This seems like it should be easy. Thanks.

推荐答案

嘿,dardub,您可以使用array_walk来验证数组中是否有特定值-array_walk遍历数组的al元素,并将提供的函数应用于它们,因此基本上您需要创建该功能.它的用法如下:

Hey dardub, you can use array_walk to verify if a particular value is within your array - array_walk iterates through al elements of you array and applys a provided function to them, so basically you would need to create that function. It is used as follows:

$arr = array(
    'one' => array('id' => 1),
    'two' => array('id' => 2),
    'three' => array('id' => 3)
);

function checkValue($value, $key)
{
    echo $value['id'];
}

array_walk($arr, 'checkValue');

您只需要将所需的任何条件/验证添加到函数中即可.

You'll just need to add to your function whatever conditionals/validations you'd need.

希望有帮助.

M.

array_walk上的PHP文档 http://www.php.net/manual/en /function.array-walk.php

PHP docs on array_walk http://www.php.net/manual/en/function.array-walk.php

这篇关于在嵌套数组中搜索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆