2011-09-10 139 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

相關問題