Page 1 of 1

Looping through mulitple arrays

Posted: 19 Oct 2020, 07:26
by Marius
I am working 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 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:

Code: Select all

array(
    [0] => Array (
        [reviewer] => name,
        [reviewerLink] => link
    ),
    [1] => Array (
        [reviewer] => name,
        [reviewerLink => link
    )
)
If an agent only has one review:

Code: Select all

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 differentiate the arrays?

Looping through mulitple arrays

Posted: 19 Oct 2020, 07:28
by Admin
Try to check if it is a multidimensional array, use count($agent, 1);, it will recursively count the array.

Code: Select all

$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
So, if count($agent, 1); is less than 3, the $agent has one review, according to your JSON format.

Code: Select all

if (count($agent, 1) <3) {
  // only one review
} else {
  // more reviews
  // do the foreach
}