简体   繁体   English

PHP:具有特定键的数组元素

[英]PHP: Array elements with a certain key

I have a PHP array like this (sans syntax): 我有一个像这样的PHP数组(sans语法):

array
(
    ['one'] => array (
                      ['wantedkey'] => 5
                      ['otherkey1'] => 6
                      ['otherkey2'] => 7
                     )
    ['two'] =>  => array (
                      ['otherkey1'] => 5
                      ['otherkey2'] => 6
                      ['wantedkey'] => 7
                     )
    ['three'] =>  => array (
                      ['otherkey1'] => 5
                      ['wantedkey'] => 6
                      ['otherkey2'] => 7
                     )
)

What's the best way to print the values for only the elements with a key of 'wantedkey' , if I'm using array_walk_recursive for example? 例如,如果我使用array_walk_recursive ,则仅打印键为'wantedkey'的元素的值的最佳方法是什么?

Thanks! 谢谢!

Wouldn't something like this work? 这样的东西行不行?

function test_print($item, $key) {
  if ($key === 'wantedkey') {
    print $item;
  }
}

array_walk_recursive($myarray, 'test_print');

Or am I missing something in your requirements? 还是我错过了您的要求? [I guess I was] [我猜我是]

So the best way I can thing of handling what you are looking for would be something like: 因此,处理您正在寻找的东西的最好方法是:

function inner_walk ($item, $key) {
  if ($key === 'wantedkey2') {
    print $item;
  }
}

function outer_walk ($item, $key) {
  if (($key === 'wantedkey1') && (is_array($item)) {
    array_walk($item,'inner_walk');
  }
}

array_walk($myarray,'outer_walk');

The problem with array_walk_recursive is that it doesn't actually tell you where you are in the array. array_walk_recursive的问题在于它实际上并未告诉您阵列中的位置。 You could in theory apply something similiar with array_walk_recursive to the above, but since you only presented a two dimensional array, using array_walk should work just fine. 从理论上讲,您可以将与array_walk_recursive类似的东西应用于上述内容,但是由于您仅呈现了二维数组,因此使用array_walk应该可以正常工作。

I may be mising something here too, but why not just foreach over them? 我可能在这里也误会了一些东西,但为什么不只是在它们上面散布呢?

foreach($myarray as $subarray) {
    echo $subarray['wantedkey'];
}

Doesn't directly answer your original question since its not using array_walk_recursive , but it would seem to do what you ask with less complexity. 由于它不使用array_walk_recursive ,因此不会直接回答您的原始问题,但是它似乎可以更array_walk_recursive地完成您所要求的工作。 Have I misunderstood? 我误会了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM