这是我用来为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
$项的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"
}
}
为什么哦,为什么会发生?
这是一个二维数组,您不必像循环的一维数组那样循环。循环时,您可以提供索引以访问内部数组。这样做:
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>';