生成数组值列表时奇怪的PHP行为
问题描述:
I have a multidimensional PHP array of the following form:
Array
(
[0] => Array
(
[id] => 45
[date] => 2013-05-16
)
[1] => Array
(
[id] => 30
[date] => 2013-12-10
)
[2] => Array
(
[id] => 26
[date] => 2014-03-27
)
[3] => Array
(
[id] => 34
[date] => 2014-03-27
)
)
I am trying to generate a list of the [id] values, separated by commas, using the following PHP code:
foreach ($my_array as $key => $value) {
if ($key == 0) {
$id_list = $value[id];
}
if ($key !== 0 ) {
$id_list .= "," . $value[id];
}
}
I was hoping this would return
45,30,26,34
...but for some reason it returns
45,30,26,26
i.e. the penultimate ID is duplicated and the final ID is missed off. I have been staring at this for a while now but I can't see where I'm going wrong. Have I missed something obvious?
我有一个以下形式的多维PHP数组: p>
数组
(
[0] =>数组
(
[id] => 45
[日期] => 2013-05-16
)
[1] = >数组
(
[id] => 30
[日期] => 2013-12-10
)
[2] =>数组
(
[id] => 26
[date] => 2014-03-27
)
[3] =>数组
(
[id] => 34
[date] => ; 2014-03-27
)
)
code> pre>
我正在尝试生成[id]值列表,以逗号分隔,使用 以下PHP代码: p>
foreach($ my_array as $ key => $ value){
if($ key == 0){
$ id_list = $ value [id];
}
if($ key!== 0){
$ id_list。=“,”。 $ value [id];
}
}
code> pre>
我希望这会返回 p>
45 ,30,26,34
code> pre>
...但由于某种原因它会返回 p>
45,30, 26,26
代码> PRE>
即 倒数第二个ID重复,最终ID丢失。 我一直在盯着这一段时间,但我看不出我哪里出错了。 我错过了一些明显的东西吗? p>
div>
答
The better solution would be to not use those if()
at all:
$ids = array();
foreach($arr as $val) {
$ids[] = $val['id'];
}
$id_str = implode(',', $ids);