Search code examples
phploopsforeach

How do I loop through this 2d array?


Well I'm relatively new to the use of PHP arrays and I have the follow array I need to loop through this array 2280 and 2307 are the identifiers.

I'm find it hard trying to come up with a foreach() that collects all the data.

Array
(
[2280] => Array
    (
        [0] => http://deals.com.au//uploads/deal_image/2706.jpg
        [1] => Yuan's Massage and Beauty
        [2] => Get Hair Free in CBD! Only $99 for SIX MONTHS worth of the latest in IPL Permanent Hair Reduction. Choose which area you want treated! Valued at $900 from Yuan's Massage and Beauty in the Heart of Melbourne's CBD. Limited vouchers available
        [3] => 99
        [4] => 900
        [5] => 801
        [6] => http://deals.com.au/1827
    )

[2307] => Array
    (
        [0] => http://deals.com.au//uploads/deal_image/2683.jpg
        [1] => Name Necklace Australia
        [2] => Style yourself like SJP! Only $29 for a STERLING Silver Name Necklace plus get FREE delivery! Valued at $75 with NameNecklace.com.au
        [3] => 29
        [4] => 75
        [5] => 46
        [6] => http://deals.com.au/Melbourne
    )
)

Solution

  • Your array snippet

    $array = array( // foreach ($array as $k=>$subarray)
    '2280' /* this is your $k */ => 
        array( /* and this is your $subarray */
            'http://deals.com.au//uploads/deal_image/2706.jpg',
    

    And now you get data you need (you had to use nested foreach since values of your array are arrays):

    foreach ($array as $k=>$subarray) {
        foreach ($subarray as $data) {
            echo $data;//of subarray
        }
    }
    

    UPDATE

    The OPs comment quistion on my answer:

    what if I wanted to be selective rather than get a massive data dump. if I echo $data how do I access specific rows?

    Well, in most cases you should associate keys and data in your array (we call it associative array in PHP).

    Example 1:

    $hex_colors = array('FF0000', '00FF00' '0000FF');
    

    Values are not assoiated with correspondent keys. PHP will assign 0,1,2... keys to arrays elements itself. In this case you would get green color's heximal value using auto-assigned by PHP 1 key: echo $hex_colors[1]; // 00FF00 and of course you should know it for sure. Usually this approach is used when you have strict data structure like array(red, green, bluee), but in most cases you better use the following approach:

    Example 2:

    $hex_colors = array('red'=>'FF0000', 'green'=>'00FF00' 'blue'=>'0000FF');
    

    heximal colors representations are associated with appropriate keys echo $hex_colors['green']; // 00FF00

    If your array was:

    $array = array(
        '2280' => array(
            'image_url' => 'http://deals.com.au//uploads/deal_image/2706.jpg',
            'product_name' => 'Yuan\'s Massage and Beauty',
            'description' => 'Get Hair Free in CBD! Only $99 for SIX MONTHS worth of the latest in IPL Permanent Hair Reduction. Choose which area you want treated! Valued at $900 from Yuan's Massage and Beauty in the Heart of Melbourne's CBD. Limited vouchers available',
            'price' => 99,
            'weight_brutto' => 900,
            'weight_netto' => 801,
            'dealer_store' => 'http://deals.com.au/1827',
            ...
    

    You would be able to access data using, let's call it "human-readable" keys:

    foreach ($array as $id=>$product) {
        echo '<a href="http://myshop.com/?product_id='.$id.'">Buy '.$product['name'].'</a>';
        echo '<img class="product_thumbnail" src="'.$product['image_url'].'" />';
        echo 'Description: '.$product['description'];
        echo 'The price is '.number_format($product['price']);
        ...
    }
    

    It is well-suited for reading rows from database, for example:

    while ($data = mysql_fetch_array($query_result_link, MYSQL_ASSOC)) { 
    // MYSQL_ASSOC flag is not necessary
    // PHP will use this flag by default for mysql_fetch_array function
    // keys of $data will be correspondent columns names returned by mysql query
        echo $data['id'];
        echo $data['title'];
        ...
    }
    

    Continue learning PHP and you will find many more situations when it's more convenient to associate keys and values.