为什么这个数组创建在php7中不起作用?

时间:2017-06-08 19:58:07

标签: php arrays foreach php-7

这是我用来为WordPress网站创建数组的代码。

foreach ($terms as $item) {
    $location_no++;
    $term_id = $item->term_id;
    $term_name = $item->name;
    $latitude = get_field('latitud', 'term_' . $term_id);
    $longitude = get_field('longitud', 'term_' . $term_id);

    // Populate the array!
    $locations[$location_no] = array (
        'id' => $location_no,
        'lat' => $latitude,
        'long' => $longitude,
        'name' => $term_name,
    );
}
echo '<pre>';
print_r($locations);
echo '</pre>';

print_r()生成:

Array
(
    [1] => Array
        (
            [id] => 1
            [lat] => 40.423560
            [long] => -3.702541
            [name] => Madrid
        )

    [2] => Array
        (
            [id] => 2
            [lat] => 40.423560
            [long] => -3.702541
            [name] => Madrid
        )

)

...

然而,当我切换到php7.1时,阵列不再有效,我得到了这个:

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

$ terms的var_dump()产生:

array(1) {
  [0]=>
  object(WP_Term)#7136 (10) {
    ["term_id"]=>
    int(28)
    ["name"]=>
    string(6) "Madrid"
    ["slug"]=>
    string(6) "madrid"
    ["term_group"]=>
    int(0)
    ["term_taxonomy_id"]=>
    int(28)
    ["taxonomy"]=>
    string(14) "trip_locations"
    ["description"]=>
    string(0) ""
    ["parent"]=>
    int(71)
    ["count"]=>
    int(5)
    ["filter"]=>
    string(3) "raw"
  }
}

为什么会发生这种情况?

2 个答案:

答案 0 :(得分:0)

它是一个二维数组,你不必像循环一维数组那样循环它。 循环时,您可以提供索引来访问内部数组。 这样做:

foreach($location as $key=>$value){
   echo $value["id"]."<br>";
   echo $value["lat"]."<br>;
   echo $value["long"]."<br>";
   echo $value["name"]."<br>";
}

答案 1 :(得分:0)

如果您尝试这种情况会怎样?

$locations = [];

foreach ($terms as $location_no => $item) {

    $term_id = $item->term_id;
    $term_name = $item->name;
    $latitude = get_field('latitud', 'term_' . $term_id);
    $longitude = get_field('longitud', 'term_' . $term_id);

    // Populate the array!
    $locations[$location_no] = [
        'id' => $location_no,
        'lat' => $latitude,
        'long' => $longitude,
        'name' => $term_name,
    ];
}

echo '<pre>';
print_r($locations);
echo '</pre>';