Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

php - Search for values in nested array

I have an array as follows

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

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.

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.

doing something like

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Hope it helps.

M.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...