gpt4 book ai didi

php - 反向迭代php关联数组

转载 作者:行者123 更新时间:2023-12-03 20:18:33 24 4
gpt4 key购买 nike

如何在 php 关联数组上反向迭代? https://stackoverflow.com/a/10777617/1032531给出非关联数组的解。

我的尝试:

$a=['5'=>'five','3'=>'three','7'=>'seven'];
var_dump($a);
foreach($a as $k=>$v){echo("$k $v\n");}
$a=array_reverse($a);
var_dump($a);
foreach($a as $k=>$v){echo("$k $v\n");}

产生以下结果:
array(3) {
[5]=>
string(4) "five"
[3]=>
string(5) "three"
[7]=>
string(5) "seven"
}
5 five
3 three
7 seven
array(3) {
[0]=>
string(5) "seven"
[1]=>
string(5) "three"
[2]=>
string(4) "five"
}
0 seven
1 three
2 five

我希望保留 key ,然后返回:
array(3) {
[5]=>
string(4) "five"
[3]=>
string(5) "three"
[7]=>
string(5) "seven"
}
5 five
3 three
7 seven
array(3) {
[7]=>
string(5) "seven"
[3]=>
string(5) "three"
[5]=>
string(4) "five"
}
7 seven
3 three
5 five

最佳答案

只需使用 $a=array_reverse($a,true);而不是 $a=array_reverse($a);为保持关键。
array_reverse()有第二个可选参数用于保留 key 。默认值为假。

阅读 doc here

关于php - 反向迭代php关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38225113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com