这是$ distribution数组
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
)
)
这是$ sold数组
Array
(
[ASCM72X36] => Array
(
[item_code] => ASCM72X36
[quantity] => 1.0
)
[ASCM72X60] => Array
(
[item_code] => ASCM72X60
[quantity] => 1.0
)
)
所以即时比较键并使用新数量构建新的$ responce数组并过滤出数量为0的产品,如下所示
$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++;
}
然后我需要让json编码输出所以即时通讯这样做
echo json_encode($responce);
即时退出
{"data":{"0":{"item_code":"ASCM72X36","quantity":4,"selling_price":"6758.00"},"2":{"item_code":"ASCM72X60","quantity":4,"selling_price":"8544.00"}}}
问题是在json中得到“0”,“2”等。如何在不使用“0”和“2”之类的情况下防止这种情况并获得出局......?
{"data":{"item_code":"ASCM72X36","quantity":4,"selling_price":"6758.00"},{"item_code":"ASCM72X60","quantity":4,"selling_price":"8544.00"}}
答案 0 :(得分:2)
似乎你正在编码对象。 你想要的方式必须编码数据变量
echo json_encode(array("data"=>$responce->data));
如果编码一个以字符串作为索引的数组,则该数组将成为json编码字符串中的一个对象。
Plase,试试这个:
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;
}
}
答案 1 :(得分:0)
您正在获取索引,因为您正在跳过值。即,您的数组是关联的,而不是数字。
尝试运行
$responce->data = array_values($responce->data)
最后重新编制索引。更好的是,将[$i]
放在作业中,然后执行
$responce->data[] = ....
另外,你拼错了“回复”。
如果这些都不起作用,如果您运行的是PHP 5.3.3或更高版本,请查看JSON_NUMERIC_CHECK
。 http://ca2.php.net/manual/en/function.json-encode.php