2016-05-18 7 views
0

私はFacebookのグラフapiで、json/arrayの応答を得ています。私がする必要があるのは、私が彼らのフォーマットを使用するのが快適でないのでjsonを再フォーマットすることです。foreachで配列を再フォーマットする

"ids": [ 
    { 
     "id": "id1", 
     "format": [ 
     { 
      "filter": "130x130", 
      "picture": "sample1.jpg", 
     }, 
     { 
      "filter": "130x130", 
      "picture": "sample1.jpg", 
     } 
     ] 
    }, 
     { 
     "id": "id2", 
     "format": [ 
     { 
      "filter": "130x130", 
      "picture": "sample2.jpg", 
     }, 
     { 
      "filter": "130x130", 
      "picture": "sample2.jpg", 
     } 
     ] 
    } 
] 

PHPコード: は、これは私のサンプルJSONレスポンスである

$sampleArray = //let say this is the array sample above 
$dataArray = array(); 
$dataArrayNested = array(); 
foreach($sampleArray['ids'] as $key => $value){ 
    $dataArrayNested[$key] = $value['id']; 
    $dataArrayNested[$key] = $value['format'][0]['picture'] 
} 
$dataArray['ids'] = $dataArrayNested; 

しかし、私は結果をプリントアウトする場合:

{ 
    "ids": [ 
    "id1", 
    "sample1.jpg", 
    "id2", 
    "sample2.jpg" 
    ] 
} 

この結果は、私が欲しいものは本当にないです。それはこのようにする必要があります:あなたは非該当する数値である$keyに参照のうえいる

{ 
     "ids": [ 
     { 
     "id": "id1", 
     "format" : "sample1.jpg" 
     }, 
     { 
     "id": "id1", 
     "format" : "sample1.jpg" 
     } 
     ] 
    } 

私は私のコードで何かが間違っている知っている..あなたのPHPコードで

+0

:https://jsonformatter.curiousconcept.com/](https://jsonformatter.curiousconcept [オンラインそれを解析。 com /) –

+0

私のjsonサンプルはちょうど私の質問のためのサンプルです。私のコードの本物のものが有効です – Amboom

+0

jsonの少なくとも1つの有効な部分を作るなら、それを確認することができます。 –

答えて

1

ライン4 に。

私はあなたのような何かを探しているものを考える:あなたのJSONが有効になり

<?php 
foreach($sampleArray['ids'] as $value){ 
    $key = $value['id']; 
    if (!isset($dataArrayNested[$key])) $dataArrayNested[$key] = array(); 

    $dataArrayNested[$key]['id'] = $value['id']; 
    $dataArrayNested[$key]['format'] = $value['format'][0]['picture']; 
} 
+0

ありがとう、それはうまく動作します! – Amboom

関連する問題