1

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.

2
  • By using nested loops Commented Aug 13, 2013 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. Commented Aug 13, 2013 at 21:57

3 Answers 3

2

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

Comments

2

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.

Comments

1

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 />";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.