PHP: high depth array, how do return current key n

2019-09-05 06:51发布

I have a huge array from a json_decode result (assoc set to true) and have the following code to check if (one of the arrays within, a random serial) has the key 'set_true'

$out = "";
foreach ($array as $sub) {
  //$out[] = $sub['set_true'];
  if (in_array($sub['set_true'], $sub) && $sub['set_true'] == '1' ) {
     $out[] = 'User: ' . $sub . ' has set_true = 1';
  }
}

That code lists all the users with that array key set to 1, but $sub returns 'array' and not the current key I'm on! (the random serial)

How do I return it?

标签: php arrays key
3条回答
小情绪 Triste *
2楼-- · 2019-09-05 07:33

If you are looping through an array with foreach, and want to know the key you're currently on in the loop, you can use this syntax :

foreach ($array as $key => $value) {
    // $key contains the name of the current key
    // and $value the current value
}
查看更多
我想做一个坏孩纸
3楼-- · 2019-09-05 07:37

What's up with your in_array call? I don't think that is correct. Why do you look for $sub in $sub?

查看更多
劫难
4楼-- · 2019-09-05 07:41

I think you mean:

$out = "";
foreach ($array as $key => $sub) {
  if (array_key_exists('set_true', $sub) && $sub['set_true'] == '1' ) {
     $out[] = 'User: ' . $key . ' has set_true = 1';
  }
}
查看更多
登录 后发表回答