【问题标题】:Why does this array creation not work in php7?为什么这个数组创建在 php7 中不起作用?
【发布时间】:2017-11-10 16:32:42
【问题描述】:

这是我用来为 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"
  }
}

为什么会这样?

【问题讨论】:

  • 如果你使用 var_dump($terms); 你会得到什么?
  • @RemcoK。我已经用输出修改了我的问题。

标签: php arrays foreach php-7


【解决方案1】:

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

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

【讨论】:

  • 我不太确定这段代码会去哪里,或者它是否确实会取代某些东西。
【解决方案2】:

如果您尝试这样做会发生什么?

$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>';

【讨论】:

  • 请不要使用答案来询问澄清问题。做或不做。没有“尝试”。 好的答案将始终解释所做的事情以及为什么以这种方式完成,不仅是为了 OP,也是为了 SO 的未来访问者。跨度>
  • 这会在每次迭代时覆盖数组,因此它会生成一个包含最后结果的数组
  • 我不这么认为,因为 $location_no 将是当前位置的数组的键。
  • @PatrikAlienus 好的,但是您提供的数组也包含一个键。还是你剪的?
猜你喜欢
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 2011-02-18
  • 2019-10-28
  • 1970-01-01
相关资源
最近更新 更多