0

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()?

1
  • Well @Tadeck, it's certainly nice to know I'm on the right track. :) Commented Apr 18, 2012 at 0:43

2 Answers 2

2

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

5 Comments

Should at least use OP example data.
So what if I wanted it to go something like 1A, 2A, 3A?
OP's data is far too confusing for a SIMPLE example. :) Going 1A2B3C is a little harder, but you could do this: foreach($myData[0] as $key=>$val) print $myData[0][$key].$myData[1][$key];
I suspect there's nothing SIMPLE about my solution...heh. The meaning of all this is to take json data and re-encode it as "geojson". I understand the concept fine enough -- decode json into array, use php to build the structure I need, re-encode -- I'm just having a bit of trouble wrapping my head around the logistics of it.
@DanRedux This makes sense. If I were cycling through a large data set would I use [i] instead of [0] or [1]?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.