我有这个…
$routes = array();
loop starts...
$routes[]['location1'] = MyValue1
$routes[]['location2'] = MyValue2
$routes[]['distance'] = MyValue3
...loop ends
我想要的是这个…
Array
(
[0] => Array
(
[location1] => MyValue1
[location2] => MyValue2
[distance] => MyValue3
)
[1] => Array
(
[location1] => MyValue1
[location2] => MyValue2
[distance] => MyValue3
)
}
但是我得到的是这个…
Array
(
[0] => Array
(
[location1] => MyValue1
)
[1] => Array
(
[location2] => MyValue2
)
[2] => Array
(
[distance] => MyValue3
)
[3] => Array
(
[location1] => MyValue1
)
[4] => Array
(
[location2] => MyValue2
)
[5] => Array
(
[distance] => MyValue3
)
}
正确的语法是什么?或者我是否需要添加一些计数器来计算循环的迭代次数使用$routes[$a]['distance']
之类的东西?
最简单的方法是构建子数组,然后将其添加到单个赋值中:
$routes = array();
loop starts...
$routes[] = array (
'location1' => MyValue1,
'location2' => MyValue2,
'distance' => MyValue3
);
...loop ends
每次对$routes[]
做任何事情时,都要向$routes
添加一个元素。因此,您必须执行上述操作或跟踪您正在使用的索引。
也可以这样做:
$routes=Array(
"0"=>Array
(
'location1' => 'MyValue1',
'location2' => 'MyValue2',
'distance' => 'MyValue3'
),
"1"=>Array
(
'location1' => 'MyValue1',
'location2' => 'MyValue2',
'distance' => 'MyValue3'
)
);