Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array that looks something like this:

Array
(
    [apple] => Array
        (
            [0] => 689795
            [1] => September 2012
            [2] => 689795
            [3] => September 2012
            [4] => 1113821
            [5] => June 2013
            [6] => 1122864
            [7] => July 2013
        )

    [pear] => Array
        (
            [0] => 1914898
            [1] => September 2012
            [2] => 1914898
            [3] => September 2012
            [4] => 1914646
            [5] => September 2012
            [6] => 1914898
            [7] => September 2012
        )
)

What I want to do is loop through the "apple" element and output something like this:

['September 2012', 689795],
['September 2012', 689795],
['June 2013', 1113821],
['July 2013', 1122864],

How can I accomplish this? So my main goal is to organize the dates and values together.

My array data is much longer than the example above, but I just need help in order to get a working code to loop through and echo something like the example above.

I've tried using foreach, however I can't get it to work. I'm fairly new to PHP.

share|improve this question
2  
What have you tried so far? –  Rocket Hazmat Aug 13 '13 at 21:53
    
By using nested loops –  Ibu Aug 13 '13 at 21:55
    
reset & 2 each() calls in a loop seems handy oldschool, foreach(array_chunk($array['apple'],2) as $combo){} is also a possibility. –  Wrikken Aug 13 '13 at 21:57

3 Answers 3

up vote 1 down vote accepted

I would use array_chunk for something like this, probably the smallest and cleanest code.

foreach (array_chunk($arr['apple'], 2) as $row) {
    echo "['$row[1]', $row[0]],<br />";
}
share|improve this answer

If your 'inner' array has always 8 elements, use an outer foreach to iterate through the fruits and a inner for loop:

foreach ($array as $fruit) {

    for ($i == 1; $i <= 7; $i += 2) {

        echo $fruit[$i] . ", " . $fruit[$i-1] . "<br />";

    } // for
} // foreach
share|improve this answer

Do this:

foreach ($first_array as $first_key=>$first_val) {
    foreach ($first_val as $second_key=>$second_val){
        echo $second_val;
    }
}

This will loop over your first array. Then for each value you get from the first loop (which is your nested array), you do the for loop again.

Now your $second_val is your "key" first time and "date" the second time.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.