我想将一个数组嵌套在另一个数组中,我的代码将类似于这个
array(
'type' => 'FeatureCollection',
'features' => array(
array(
'type' => 'Feature',
'geometry' => array(
'coordinates' => array(-94.34885, 39.35757),
'type' => 'Point'
), // geometry
'properties' => array(
// latitude, longitude, id etc.
) // properties
), // end of first feature
array( ... ), // etc.
) // features
)
其中外部部分(功能)封装了许多其他数组。我需要遍历从我已经解码的 json 文件中提取的变量——我将如何遍历这些数据集?foreach()
?
你知道数组子级的深度/数量吗?如果您知道深度是否始终保持不变?如果这两个问题的答案都是肯定的,那么foreach应该可以解决问题。
$values = array(
'type' => 'FeatureCollection',
'features' => array(
array(
'type' => 'Feature',
'geometry' => array(
'coordinates' => array(-94.34885, 39.35757),
'type' => 'Point'
), // geometry
'properties' => array(
// latitude, longitude, id etc.
) // properties
), // end of first feature
array('..'), // etc.
) // features
);
foreach($values as $value)
{
if(is_array($value)) {
foreach ($value as $childValue) {
//.... continues on
}
}
}
但是,如果这两个问题的答案是否定的,我会使用递归函数和foreach,就像这样。
public function myrecursive($values) {
foreach($values as $value)
{
if(is_array($value)) {
myrecursive($value);
}
}
}
Nested foreach。
$myData = array( array( 1, 2, 3 ), array( 'A', 'B', 'C' ) )
foreach($myData as $child)
foreach($child as $val)
print $val;
将打印 123ABC。