php while 循环遍历数组

发布于 2024-11-30 11:13:00 字数 665 浏览 0 评论 0原文

我试图循环遍历子数组(它是多维数组的一部分)并检查是否有一对键/值。如果找到该对,我想返回找到它的子数组的键。

不幸的是,key() 函数似乎无法与 foreach 一起使用。

我如何更改此代码以使用 while 循环?

如果您有更好的建议请告诉我。

foreach ($subarray as $subkey => $subvalue) {           
    if ($subkey == 'key_value' AND $subvalue = 'value') {
        return key($subarray);
    }
}

数组键不是数字。这是一个示例:

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

搜索名为“something”的“title”,该函数应返回“books”,因为这是找到子键/值对的键。

感谢您的帮助。

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 ($subarray 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮生面具三千个 2024-12-07 11:13:00
$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;
  }
}
$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;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文