2011-09-10 3 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 
     ) 
) 

であり、これは非常にキーを比較し、新たな量で新しい$ responceアレイを構築IMと以下のような量0製品をフィルタリング$販売アレイ

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

     [ASCM72X60] => Array 
      (
       [item_code] => ASCM72X60 
       [quantity] => 1.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エンコードを取得する必要があります3210
echo json_encode($responce); 

イムが出てき問題はイムJSONで.. "0"、 "2" などになっている

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

のように置きます。どのようにそれを防ぐためにそれらの "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[] = .... 

を行う。また、あなたは間違って「応答」を綴ります。

PHP 5.3.3以降を実行している場合は、JSON_NUMERIC_CHECKをご覧ください。 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

関連する問題