user4422481
user4422481

Reputation:

Fetch values from multi dimensional array

I need to fetch data from the array that I got through

print_r($result);

The array I got is

Array
(
    [0] => Array
        (
            [id] => 
            [Location] => Array
                (
                    [img] => 177223
                    [name] => 
                )

            [Max] => 
            [Total] => 
            [Description] => Array
                (
                    [Pre] => 
                    [Updated] => 
                    [Program] => Array
                        (
                            [Schedule] =>
                        )
                )

            [Staff] => Array
                (
                    [FirstName] => 
                )
        )
)

I used this code

if (!empty($result)) 
    {
        foreach ($result as $res) 
            {
                $Max = $res['Max'];
                echo $Max;
                echo "<br>";
                    if(isset($res['Location']))
                        {
                            foreach($res['Location'] as $loc)
                                    {
                                        $img= $loc['img'];
                                        echo $img;
                                        echo "<br>";
                                    }   
                        }
            } 
    }       

I am getting correct value for the first array (I.e Max etc) but not for Location, Description and Staff, can anyone correct my code

Upvotes: 1

Views: 80

Answers (2)

Horaland
Horaland

Reputation: 897

You dont need to foreach through location, just access it's elements directly:

if(isset($res['Location']))

     {
          $img= $res['Location']['img'];
          echo $img;
          echo "<br>";
     }   

Or somethig like that.

Upvotes: 0

steven
steven

Reputation: 4875

Location is not an array of arrays. It is just an associative array.

if (!empty($result)) {
    foreach ($result as $res) {
            $Max = $res['Max'];
            echo $Max;
            echo "<br>";
            if(isset($res['Location'])) {
                 $img= $res['Location']['img'];
                 echo $img;
                 echo "<br>";
            }
     } 
}     

Upvotes: 3

Related Questions