Michael C.
Michael C.

Reputation: 2520

Looping through an array inside another array php

I want to nest an array inside another array, my code will be similar to this

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
)

Where the outer section (features) encapsulates many other arrays. I need to loop through variables pulled from a json file which I've already decoded -- how would I loop through these sets of data? A foreach()?

Upvotes: 0

Views: 1091

Answers (2)

ro ko
ro ko

Reputation: 2986

Do you know the depth/no of children of the array? If you know does the depth always remains same? If answer to both of the question is yes then foreach should do the trick.

$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 
        }
    }
}

But If answer of any of those two question is no I would use a recursive function along with foreach, something like this.

public function myrecursive($values) {
    foreach($values as $value)
    {
        if(is_array($value)) {
            myrecursive($value);
        }
    }
}

Upvotes: 2

DanRedux
DanRedux

Reputation: 9359

Nested foreach.

$myData = array( array( 1, 2, 3 ), array( 'A', 'B', 'C' ) )

foreach($myData as $child) 
  foreach($child as $val)
    print $val;

Will print 123ABC.

Upvotes: 0

Related Questions