I'm having problems getting values in my multidimensional arrays
我无法在多维数组中获取值
Array
(
[0] => Array
(
[name] => Brandow & Johnston, Inc.
[lat] => 34.051405
[lng] => -118.255576
)
[1] => Array
(
[name] => Industry Metrolink Train Station
[lat] => 34.00848564346
[lng] => -117.84509444967
)
[2] => Array
(
[name] => The Back Abbey
[lat] => 34.095161
[lng] => -117.720638
)
[3] => Array
(
[name] => Eureka! Burger Claremont
[lat] => 34.094572563643
[lng] => -117.72184828904
)
)
Lets say I have an array such above
假设我有一个这样的数组。
And I'm using a foreach loop such as below
下面我用的是foreach循环
foreach($_SESSION['array'] as $value){
foreach($valueas $key_location=> $value_location){
if($key_location = "name"){$fsq_name = $value_location;}
$fsq_lat = $value_location["lat"];
$fsq_lng = $value_location["lng"];
echo "<i>".$fsq_lat."</i><br/>";
}
}
I've tried using the if statement, or using $value_location["lat"];
but its not producing the correct values.
我尝试过使用if语句,或者使用$value_location["lat"];但它并没有产生正确的价值。
If I do if($key_location === "lng"){$fsq_lng = $value_location;}
with three equal
signs, it'll give me errors for a few iterations and then produce the lng
results. if I just do one equal
sign and echo it out, it'll give me the name
key as well.
如果我这样做($key_location === "lng"){$fsq_lng = $value_location;}有三个相等的符号,它会在几次迭代中给我错误,然后产生lng结果。如果我做一个等号,并把它重复出来,它也会给我命名键。
Am I missing something?
我遗漏了什么东西?
Thanks
谢谢
2 个解决方案
#1
6
You don't actually need the inner foreach
loop. The outer one is sufficient, since it iterates over arrays. The inner arrays can be accessed by key inside the outer foreach
.
实际上并不需要每个循环的内部。外部的是充分的,因为它遍历数组。内部数组可以通过键在外部foreach中访问。
foreach($_SESSION['array'] as $value){
$fsq_name = $value["name"];
$fsq_lat = $value["lat"];
$fsq_lng = $value["lng"];
echo "<i>".$fsq_lat."</i><br/>";
// Actually none of the above assignments are necessary
// you can just:
echo "<i>".$value["lat"]."</i><br/>";
}
#2
0
Maybe refactor a bit?
也许重构一点?
foreach($_SESSION['array'] as $value)
{
// pull the lat and lng values from the value
$fsq_lat = $value["lat"];
$fsq_lng = $value["lng"];
$fsq_name = $value["name"];
echo "<i>".$fsq_lat."</i><br/>";
}// foreach
#1
6
You don't actually need the inner foreach
loop. The outer one is sufficient, since it iterates over arrays. The inner arrays can be accessed by key inside the outer foreach
.
实际上并不需要每个循环的内部。外部的是充分的,因为它遍历数组。内部数组可以通过键在外部foreach中访问。
foreach($_SESSION['array'] as $value){
$fsq_name = $value["name"];
$fsq_lat = $value["lat"];
$fsq_lng = $value["lng"];
echo "<i>".$fsq_lat."</i><br/>";
// Actually none of the above assignments are necessary
// you can just:
echo "<i>".$value["lat"]."</i><br/>";
}
#2
0
Maybe refactor a bit?
也许重构一点?
foreach($_SESSION['array'] as $value)
{
// pull the lat and lng values from the value
$fsq_lat = $value["lat"];
$fsq_lng = $value["lng"];
$fsq_name = $value["name"];
echo "<i>".$fsq_lat."</i><br/>";
}// foreach