Jump to content

using foreach to access data


ruraldev

Recommended Posts

I am trying in vain to access the numbers in the "sims" array using the code below, I have tried various numbers of nested foreach loops but get errors every time, can anyone help point me in the correct direction please.

 

Thanks

 

Gordon

$stock = (array(1) 
	{ ["stock"]=> array(2) 
		{ [0]=> array(2) 
			{ ["operator"]=> string(3) "ECL" 
				["sims"]=> array(51) 
					{ 
					[0]=> int(8944122650438410000) 
					[1]=> int(8944122650438409000) 
					[2]=> int(8944122650438409000)
		 			} 
		 	} 
		[1]=> array(2) { 
			["operator"]=> string(2) "JT" 
				["sims"]=> NULL 
} } } )


foreach ($stock as $key1 => $item1)
            { 
                foreach($item1 as $key2 => $item2)
                { 
                		foreach($item2 as $key => $value)
                		{
                    		echo $value[sims] . "</br>";
                		}
            	}
			}
Link to comment
https://forums.phpfreaks.com/topic/292997-using-foreach-to-access-data/
Share on other sites

It's an important skill to be able to read dumps like this.

$stock = (array(1)
$stock is an array with one item.

{ ["stock"]=> array(2)
The key is "stock" and the value is another array, this time with two items.

{ [0]=> array(2)
The first key is 0 suggesting the parent array is something you should foreach over. The value is another array.

{ ["operator"]=> string(3) "ECL" 
  ["sims"]=> array(51)
In the array are two items, "operator" (a string) and "sims" (yet another array).

 

All together,

foreach ($stock["stock"] as $stock) {
    foreach ($stock["sims"] as $sim) {

Thank you for not only taking the time to give me the correct code but also to provide some workings which I can use to understand the process.

 

It returns the values I want but for some reason I get an error at the bottom of the page: Warning: Invalid argument supplied for foreach() in .......

 

For line:   foreach ($stock["sims"] as $sim)

 

Any ideas?

    foreach ($stock["stock"] as $stock) 
    		{
    			foreach ($stock["sims"] as $sim)
    				{
                    echo $sim . "</br>";
            		}
			}

Most likely because the second item in the $stock array does not contain a sims array. You to check to see if $stock['sims'] is an array before looping through it with foreach

foreach ($stock["stock"] as $stock) 
{
    // check to see if there is a sims array for this item
    if(is_array($stock['sims']))
    {
        foreach ($stock["sims"] as $sim)
        {
            echo $sim . "</br>";
        }
    }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.