How to get correct json output in this case?
this is the $distribution array
Array
(
[ASCM72X36] => Array
(
[item_code] => ASCM72X36
[quantity] => 5
[selling_price] => 6758.00
)
[ASCM72X48] => Array
(
[item_code] => ASCM72X48
[quantity] => 5
[selling_price] =>
)
[ASCM72X60] => Array
(
[item_code] => ASCM72X60
[quantity] => 5
[selling_price] => 8544.00
)
)
and this is the $sold array
Array
(
[ASCM72X36] => Array
(
[item_code] => ASCM72X36
[quantity] => 1.0
)
[ASCM72X60] => Array
(
[item_code] => ASCM72X60
[quantity] => 1.0
)
)
so im comparing keys and building new $responce array with new quantity and filter out quantity 0 products like below
$i=0;
foreach($distribution as $key => $new_distribution)
{
$newqty = $new_distribution['quantity'] - $sold[$key]['quantity'];
if( $newqty != 0 && $new_distribution['selling_price'] != ""){
$responce->data[$i]['item_code'] = $new_distribution['item_code'];
$responce->data[$i]['quantity'] = $newqty;
$responce->data[$i]['selling_price'] = $new_distribution['selling_price'];
}
$i++;
}
then i need to get json encode out put so im doing it like this
echo json_encode($responce);
im getting out put like
{"data":{"0":{"item_code":"ASCM72X36","quantity":4,"selling_price":"6758.00"},"2":{"item_code":"ASCM72X60","quantity":4,"selling_price":"8544.00"}}}
problem is im getting a "0", "2" etc.. in json. how to prevent that and get the out put like without those "0" s and "2" etc...?
{"d开发者_Python百科ata":{"item_code":"ASCM72X36","quantity":4,"selling_price":"6758.00"},{"item_code":"ASCM72X60","quantity":4,"selling_price":"8544.00"}}
seems that you are encoding the object. the way you want you must encode the data variable
echo json_encode(array("data"=>$responce->data));
If your encode an array that has strings as indices, the array becomes an object in the json encoded string.
Plase, try this way:
foreach($distribution as $key => $new_distribution)
{
$newqty = $new_distribution['quantity'] - $sold[$key]['quantity'];
if( $newqty != 0 && $new_distribution['selling_price'] != ""){
$arr=array();
$arr['item_code'] = $new_distribution['item_code'];
$arr['quantity'] = $newqty;
$arr['selling_price'] = $new_distribution['selling_price'];
$responce->data[] = $arr;
}
}
You're getting indices because you're skipping values. i.e., your array is associative, not numeric.
Try running
$responce->data = array_values($responce->data)
At the end to reindex it. Better yet, drop the [$i]
in your assignments and just do
$responce->data[] = ....
Also, you're spelling "response" wrong.
If none of that works, take a look at JSON_NUMERIC_CHECK
if you're running PHP 5.3.3 or higher. http://ca2.php.net/manual/en/function.json-encode.php
精彩评论