开发者

php while loop through array

开发者 https://www.devze.com 2023-03-28 22:17 出处:网络
I\'m trying to loop through a sub array (which is part of a multidimensional array) and check if there\'s a pair of key/value. If the pair is found, I want to return the key of the sub array in which

I'm trying to loop through a sub array (which is part of a multidimensional array) and check if there's a pair of key/value. If the pair is found, I want to return the key of the sub array in which it was found.

Unfortunately it seems the key() function doesn't work with foreach.

How would I change this code to use a while loop?

If you have a better suggestion let me know.

foreach ($sub开发者_StackOverflow社区array as $subkey => $subvalue) {           
    if ($subkey == 'key_value' AND $subvalue = 'value') {
        return key($subarray);
    }
}

The array keys are not numeric. Here's a example :

$array['books'] = array('quantity' => 10, 'title' => 'Something')
$array['dvds'] = array('quantity' => 30, 'title' => 'Something else')

Searching for a "title" called "something", the function should return "books" because that's the key where the pair of sub key/value is found.

Thanks for your help.


$array['books'] = array('quantity' => 10, 'title' => 'Something');
$array['dvds'] = array('quantity' => 30, 'title' => 'Something else');

foreach($array as $key => $value) {
  if ($value['title'] === 'Something') {
    return $key;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消