When I wrote my previous post, there are some function in PHP that sent the output as Json format to be used in JsonStore component, sometimes I create the json format manually with string concatenation, looping through the data, this is quite simple actually, but I write this post because when I got an error from this json format, it make me feel a bit dizzy for example:
$query = $this->db->get('products');
$json = "{'products':[";
foreach($query->result() as $data)
{
$json .= '{"id":"'.$data->id.'",
"name":"'.$data->name.'",
"price":"'.$data->price.'",
"image":"'.$data->image.'"},';
}
$json .= "]}";
echo $json;
The problem with this code is the last row still got the comma ( , ) punctuation mark, maybe this will not cause any problem on Firefox, Chrome, Opera or Safari, but It will be a problem on IE, my experience is the ExtJS grid that using this data won’t show, if I want to keep creating the json like that I should add a conditional statement on the looping, and the code becoming like this
$query = $this->db->get('products');
$json = "{'products':[";
foreach($query->result() as $key => $data)
{
$json .= '{"id":"'.$data->id.'",
"name":"'.$data->name.'",
"price":"'.$data->price.'",
if ($key == $query->num_rows() - 1)
{
$json .= '"image":"'.$data->image.'"}';
}
else
{
$json .= '"image":"'.$data->image.'"},';
}
}
$json .= "]}";
echo $json;
But sometimes I forgot that PHP have a great json_encode function, and this will make us easier when creating json format from an array
$query = $this->db->get('products');
$product_arr = array();
foreach($query->result() as $key => $data)
{
$product_arr[] = array(
'id' => $data->id,
'name' => $data->name,
'price' => $data->price,
'image' => $data->image
);
}
echo json_encode(array('products' => $product_arr));
The result is the same but I do not know yet which one is performing faster, well for now I’m just using the easier one.





No Comment Leave a Comment Subscribe RSS