2011-09-10 140 views
0

这是$分布阵列如何在这种情况下获得正确的json输出?

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 
     ) 
) 

,这是$出售阵列

Array 
    (
     [ASCM72X36] => Array 
      (
       [item_code] => ASCM72X36 
       [quantity] => 1.0 
      ) 

     [ASCM72X60] => Array 
      (
       [item_code] => ASCM72X60 
       [quantity] => 1.0 
      ) 
) 

这样的IM比较键和建立新的$性反应的数组新的数量,并筛选出数量一样低于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编码出来把这样的IM做这样

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"}}} 

问题是即时得到一个 “0”, “2” 等。在JSON。如何防止那些“0”和“2”等等......?

{"data":{"item_code":"ASCM72X36","quantity":4,"selling_price":"6758.00"},{"item_code":"ASCM72X60","quantity":4,"selling_price":"8544.00"}} 
+0

的0和2从我可以看到是“数据”数组的数组索引。你为什么要删除它们? –

回答

0

你越来越指数,因为你跳过值。即您的数组是关联的,而不是数字。

尝试运行

$responce->data = array_values($responce->data) 

在年底重新索引它。更重要的是,滴在你的任务的[$i],只是做

$responce->data[] = .... 

此外,你拼写“回应”是错误的。

如果没有这样的作品,看看JSON_NUMERIC_CHECK如果你正在运行PHP 5.3.3或更高版本。 http://ca2.php.net/manual/en/function.json-encode.php

+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; 
    } 

}

+0

+1。就是这个。下次尝试写在正确的字母案件,因为你会看起来很酷,对吧?对! :) – Shef

+0

事情是我需要的数据{“数据”:{部分。如果我像你说的那样去除它。 –

+0

请检查新的代码。 – renato

相关问题