Sumit Bhatia Sumit Bhatia - 6 months ago 9
PHP Question

How to fetch multi-dimensional mix array in php?

I have this array stored in a variable :-

Array (
[0] => Array (
[date] => 06/01/2016 - 06/30/2016
[0] => Array ( [0] => 1 [1] => 34 [2] => 2 [3] => 55 )
[1] => Array ( [0] => 2 [1] => 55 [2] => 55 [3] => 100 )
[2] => Array ( [0] => 3 [1] => 60 [2] => 100 [3] => 500 )
)
)


here is my code to print it :

foreach($tables as $table)
{
foreach($table as $tier)
{
echo $tier[0]."<br>";
echo $tier[1]."<br>";
echo $tier[2]."<br>";
echo $tier[3]."<br>";
}
}


This is what it's printing:

0
6
/
0
1
34
2
55
2
55
55
100
3
60
100
500


This is what I'm expecting:

1
34
2
55
2
55
55
100
3
60
100
500


How can I get the desired result using
foreach()
?

Answer

The problem is that the date field is interpreted as a tier. Skip non-numeric tiers like this:

foreach ($tables as $table)
{
    foreach ($table as $index => $tier)
    {
       if (!is_numeric($index))
           continue;

        echo $tier[0]."<br>";
        echo $tier[1]."<br>";
        echo $tier[2]."<br>";
        echo $tier[3]."<br>";
    }
}

Here's an example of this working:

php > $tables = array(0 => array('date' => '06/01/2016 - 06/30/2016', 0 => array(1, 34, 2, 55), 1 => array(2, 55, 55, 100), 2 => array(3, 60, 100, 500)));

php > foreach ($tables as $table)
php > {
php {     foreach ($table as $index => $tier)
php {     {
php {        if (!is_numeric($index))
php {            continue;
php {
php {         echo $tier[0]."<br>";
php {         echo $tier[1]."<br>";
php {         echo $tier[2]."<br>";
php {         echo $tier[3]."<br>";
php {     }
php { }
1<br>34<br>2<br>55<br>2<br>55<br>55<br>100<br>3<br>60<br>100<br>500<br>
php >