0

I am working with the Zillow API to return reviews for a list of Agents. I have a foreach loop that then pulls the list of reviews for each agent. The list is returned as JSON. I then run a foreach loop on the JSON results to display the reviews individually. Everything works great except, a specific agent only has 1 review and it is throwing a foreach error.

Here is a very simple example return:

If an agent has multiple reviews:

array(
    [0] => Array (
        [reviewer] => name,
        [reviewerLink] => link
    ),
    [1] => Array (
        [reviewer] => name,
        [reviewerLink => link
    )
)

If an agent only has one review:

array([reviewer] => name [reviewerLink] => link)

I have tried using count(), but on an array with only 1 review, it counts the total keys since there is no index.

I need a simple way to differentiate the arrays so I don't use a foreach loop on the agents with only 1 review.

Is there a way to force the array to have an index? Or another way to differentiate the arrays?

Cid
  • 14,968
  • 4
  • 30
  • 45
RiotAct
  • 743
  • 9
  • 33

3 Answers3

2

If you have only one review, the key reviewer exists. So you can check it with the function array_key_exists if you have only one or more.

Try this code example:

if (array_key_exists('reviewer', $array)) {
  // only one review
} else {
  // more reviews
  // do the foreach
}
Robin Gillitzer
  • 1,603
  • 1
  • 6
  • 17
  • 1
    Make sure that your code for processing the review is a function or you could end with 2 places where the review data is processed. – Nigel Ren Oct 19 '20 at 07:03
2

According to the documentation, there is a reviewCount field as part of the result set, so check this before the foreach and convert it to an array if only 1 item...

if ( $json['reviewCount'] == 1 )  {
    $array = [$array];
}

or if your json is an object...

if ( $json->reviewCount == 1 )  {
    $array = [$array];
}

this will mean that all versions are an array of reviews for the foreach.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

Try to check if it is a multidimensional array, use count($agent, 1);, it will recursively count the array. So, if count($agent, 1); is less than 3, the $agent has one review.

$ag1 =[
  0 =>[
    'reviewer' => 'name',
    'reviewerLink' => 'link'
  ],
  1 =>[
    'reviewer' => 'name',
    'reviewerLink' => 'link'
  ]
];

$ag2 =[
  'reviewer' => 'name',
  'reviewerLink' => 'link'
];

echo count($ag1, 1);  // 6
echo count($ag2, 1);  // 2

Just check:

if (count($agent, 1) <3) {
  // only one review
} else {
  // more reviews
  // do the foreach
}
CoursesWeb
  • 4,179
  • 3
  • 21
  • 27