John John - 2 months ago 14
PHP Question

PHP for each loop doesn't work if only one result found

I use simplexml to take an xml results page and turn it into an array. Then I use a foreach loop to go through the array records.

The problem is if there is only one result in the array the foreach loop doesnt happen, doesnt display any information.

I have to detect if there is only one row or more than one row and depending on that either use a foreach loop or not.

Wanted to see if there is an easier way so I dont have so much code and everything fits in a foreach loop.

Here is an example:

$result = $data->params->results;
$result_count = intval($data->params->totalcount);

if($result_count > 1)
{
foreach(results AS $curr_result)
{
$result_name = $curr_result->name;
}
}
else if($result_count == 1)
{
$result_name = $result->name;
}


Edit:
I added the results variable, this is example code and in my hast I didnt go over the code to make sure it was correct. If there is only one result the array looks like this:

["fld1"]=>
string(6) "value1"
["fld2"]=>
string(6) "value2"
["fld3"]=>
string(6) "value3"

If there is more than one result it looks like this:

[0]=>
["fld1"]=>
string(6) "value1"
["fld2"]=>
string(6) "value2"
["fld3"]=>
string(6) "value3"
[1]=>
["fld1"]=>
string(6) "value1"
["fld2"]=>
string(6) "value2"
["fld3"]=>
string(6) "value3"


Again just a quick example, Im sure the code above isnt "correct" per say but it should give enough info to understand what Im talking about.

Answer

Well this is what I did to get it to work:

$result = $data->params->results;
$result_count = count($result);

if($result_count == 1)
{    
$results_array[0] = $result;
}else
{
$results_array = $result;
}

//loop through $results_array

Sorry if my information wasnt detailed enough and confusing, if you have a better way of doing this please let me know!

Comments