I was answering this question today using array_walk_recursive(), and given the OP's posted sample input, my answer was spot on. However, when the OP used it on the larger, real array some glitchy behavior was discovered while conditionally checking keys with ==. In the end, using === was enough to fix the issue.
Here is a minimal demonstration (Demo Link):
$array=[
'key1'=>[
['key1A'=>'v1'],
['key1B'=>'v2'],
['key1C'=>'v3']
],
'key2'=>[
[0=>'v4'],
[1=>'v5'],
[2=>'v6']
],
'key3'=>[
["0"=>'v7'],
["1"=>'v8'],
["2"=>'v9']
]
];
echo "Leafy nodes:\n-----\n";
array_walk_recursive($array,function($v,$k)use(&$result1){
echo "$k => $v\n";
if($k=='key1B'){ // buggy behavior with ==
if(!isset($result1[$v])){$result1[$v]=0;}
++$result1[$v];
}
});
array_walk_recursive($array,function($v,$k)use(&$result2){
//echo "$k => $v\n";
if($k==='key1B'){ // no trouble with ===
if(!isset($result2[$v])){$result2[$v]=0;}
++$result2[$v];
}
});
echo "\nIncorrect key-matching with ==\n";
var_export($result1);
echo "\nCorrect key-matching with ===\n";
var_export($result2);
Output:
Leafy nodes:
-----
key1A => v1
key1B => v2
key1C => v3
0 => v4
1 => v5
2 => v6
0 => v7
1 => v8
2 => v9
Incorrect key-matching with ==
array (
'v2' => 1,
'v4' => 1,
'v7' => 1,
)
Correct key-matching with ===
array (
'v2' => 1,
)
The behavior seems to be that "zero-ish" keys are matching key1B. If [0=>'v4'] is commented out, then v5 isn't pushed into $result1; so it is not about key position in the subarray, rather the onus is on the zero key.
I didn't find anything discussing this on SO.
I didn't find anything when I searched for array_walk_recursive() at https://bugs.php.net
What I'd like to know is:
- Is this is a bug or am I just misunderstanding something? If this is not a bug, please explain why this is correct behavior.
- Has this already been reported (and I just didn't find it)?
- I've never reported a php bug before, so I am hesitant to do so, should I go ahead and do so?
- Should I post a comment at http://ift.tt/29G3gKe ? The only other comment similar to what I am saying is at the very bottom (from 10 years ago) that is speaking to a now non-existent poster.
Finally, if this not a bug, then I hope my post will help others to identify and avoid this potential gotcha.
Aucun commentaire:
Enregistrer un commentaire