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

为什么这个数组创建在php7中不起作用?,php,arrays,foreach,php-7,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_' . $te

这是我用来为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>';
但是,当我切换到php7.1时,阵列不再工作,我得到的是:

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"
  }
}
$terms的var_dump()会产生以下结果:

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

为什么会发生这种情况?

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

foreach($key=>$value的位置){
echo$value[“id”]。“
”; echo$value[“lat”]。“
”; echo$value[“long”]。“
”; echo$value[“name”]。“
”; }
如果您尝试此操作,会发生什么情况?

$locations=[];
foreach($location\u no=>$item形式的术语){
$term\u id=$item->term\u id;
$term\u name=$item->name;
$latitude=get_字段('latitud','term_'.$term_id);
$longitud=get_字段('longitud','term_'.$term_id);
//填充数组!
$locations[$location\u no]=[
'id'=>$location\u no,
“纬度”=>$LATIONE,
“long”=>$longitude,
'name'=>$term\u name,
];
}
回声';
打印(位置);
回声';

如果您使用var_dump($terms);,您会得到什么@雷姆科克。我已经用输出修改了我的问题。请不要使用答案来询问澄清问题。做或不做。没有“尝试”。一个好的答案总是会解释做了什么以及为什么这样做,不仅是为了OP,也是为了SO的未来访问者。这会在每次迭代中覆盖数组,因此它会生成一个带有最后一个结果的数组。我不这么认为,因为$location\u no将是当前位置数组的键。@PatrikAlienus好的,但您提供的数组也包含一个键。还是你删掉了?我不太确定这段代码会去哪里,或者它是否真的会取代某些东西。
foreach($location as $key => $value){
   echo $value["id"]."<br>";
   echo $value["lat"]."<br>";
   echo $value["long"]."<br>";
   echo $value["name"]."<br>";
}
$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>';