在多维数组中返回数组数据的正确方法?

时间:2016-02-24 17:18:00

标签: php arrays post multidimensional-array

从多维数组中的数组中获取所有数据的正确方法是什么?

Array
(
[0]Array
    (
        [0] Array
            (
                [day] 3/1/2016
                [start1] 12:15am
                [end1] 1:15am
                [start2] 
                [end2] 
            )

        [1] Array
            (
                [day] 3/2/2016
                [start1] 12:00am
                [end1] 1:00am
                [start2] 
                [end2] 
            )

        [2] Array
            (
                [day] 3/3/2016
                [start1] 12:00am
                [end1] 12:00am
                [start2] 
                [end2] 
            )

    )

)

我想循环并获取每个嵌套数组的所有信息,但我似乎遇到了一个未定义的索引错误。

foreach($timeArray as $day){
echo "Day: " + $day['day'] + "Start1: " + $day['start1'] + "End1: " + $day['end1'] + "Start2: " + $day['start2'] +"End2: " + $day['end2'];
}

3 个答案:

答案 0 :(得分:0)

如果$timeArray是完整数组,那么

  • $timeArray[0]是其下方的数组,其中包含所有日期
  • $timeArray[0][0]是其下方数组的第一个元素,也就是第一天
  • $timeArray[0][0]["day"]包含值3/1/2016

另一个注意事项是你错误地连接了你的字符串:

  • "Text " + $variable + " Text" =错误
  • "Text $variable Text" = right
  • "Text {$variable["key"]} Text" =也正确

所以每天访问:

foreach($timeArray[0] as $day){
    echo "Day: {$day['day']}",
         "Start1: {$day['start1']}",
         "End1: {$day['end1']}",
         "Start2: {$day['start2']}",
         "End2: {$day['end2']}";
}

参考:

答案 1 :(得分:0)

看起来您的数组有2个级别,假设您的示例是数组的全部内容,这将起作用

PHP中的串联字符也是.而不是+

foreach($timeArray[0] as $day){
    echo "Day: " . $day['day'] . 
         "Start1: " . $day['start1'] . 
         "End1: " . $day['end1'] . 
         "Start2: " . $day['start2'] . 
         "End2: " . $day['end2'];
}

您还可以利用双引号字符串将扩展变量这样的事实

foreach($timeArray[0] as $day){
    echo "Day: {$day['day']} Start1: {$day['start1']} End1: {$day['end1']} ";
    echo "Start2: {$day['start2']} End2: {$day['end2']}";
}

或者如果你不引用数组名称

foreach($timeArray[0] as $day){
    echo "Day: $day[day] Start1: $day[start1] End1: $day[end1] ";
    echo "Start2: $day[start2]} End2: $day[end2]";
}

答案 2 :(得分:0)

你可以通过这个阅读你的数组:

foreach ($your_arr as $key_internal=>$arr_internal){
        foreach ($arr_internal as $key=>$value){
             echo $value['day'];
             ......
        }
}