I believe I have been writing some inefficient code here, but can't seem to figure out a more efficient way of writting it.
This often happens with json output, though I've had the issue with some html or xml output as well.
I run a query in my database which brings back an array. Say a persons favorite foods. php's mysql_fetch_assoc returns
Array([person]=>john [food]=>chocolate) Array([person]=>john [food]=>pizza) Array([person]=>john [food]=>coffee) Array([person]=>susan [food]=>licorice)
To create my json or html, i've been looping through looking for unique persons, and then adding the food like this
$jsonOut=''
$personAdd='';
while($gotArray=mysql_fetch_assoc(foodArray)){
if($personAdd!='$gotArray['person']){
$jsonOut.="person: $gotArray['person'], foods{";
}
$jsonOut.="food:$gotArray['food'],";
rtrim(jsonOut,',');
$jsonOut.="}";
$personAdd=$array['person'];
}
Now, this isn't a big deal when you only have one value that is repeated constantly in the mysql response, but when you start having 4 or 5 columns where the values are the same, it starts to get quite verbose.
Is there a better way to do this?
-------------Clarifying what the output should look like ----------------- The final json for the above arrays should look like this
[
{
"person": "john",
"foods": [
{
"food": "chocolate",
"food": "pizza",
"food": "coffee"
}
]
},
{
"person": "susan",
"food": "licorice"
}
]
or susan would have "foods": [{"food":"licorice"}] something like that.