doufu1939 2014-09-12 16:26
浏览 41
已采纳

生成数组值列表时奇怪的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?

  • 写回答

1条回答 默认 最新

  • douqiang3768 2014-09-12 16:29
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?