Search code examples
phpamazon-web-servicesmultidimensional-arrayamazon-rekognition

Error while accessing multi-dimensional associative array in PHP (AWS/ResulData)


I've been trying to implement Celebrity Recognition via AWS Rekognition using PHP. I was able to get the ResultData using,

$result = $client->recognizeCelebrities();

And I converted the $result to an array using,

$postResult = (array) $result;

I tried to print the array $postResult using,

echo '<pre>';
print_r($postResult);
echo '</pre>';

and it printed something similar to,

Array
(
 [Aws\Resultdata] => Array
 (
   [CelebrityFaces] => Array
   (
     [0] => Array
     (
      [Name] => Emily Blunt                            
     )
   )
  )
)

I wanted to print only the value 'Name'. So I used,

echo $postResult['Aws\Resultdata']['CelebrityFaces'][0]['Name']; 

But it throws an error as, Undefined index: Aws\Resultdata

I also tried using the foreach loop, but it results in the same error

foreach ($postResult as $array) {
    echo $array['Name'];
}

Here is the output for $result,

Aws\Result Object
 (
  [data:Aws\Result:private] => Array
  (
   [CelebrityFaces] => Array
   (
    [0] => Array
    (
     [Name] => Emily Blunt                         
    )                          
   )
  )
 )

I've just started using PHP a few days back, so I'm just a beginner. And also I tried searching for a specific answer but it always threw the same error.

Any help would be appreciated!


Solution

  • The $result is the object of class Aws\Result. According to this documentation the following should work:

    $celebFaces = $result->get('CelebrityFaces');
    foreach($celebFaces as $face) {
        echo $face['Name'];
    }