使用PHP在指定位置合并2个JSON

时间:2015-06-26 08:02:19

标签: php mysql json

我有两个mysql表中的2个JSON数组,即db_eventsdb_ads

来自db_events的JSON值内部,我想分别从位置5的db_ads和位置10的第二个值添加第一个JSON值。

我该如何实现呢?这是可能的。

db_events中的JSON是,

{
  "events_from_category": [
    {
      "id": "1",
      "name": "Demo Event"
    },
    {
      "id": "2",
      "name": "Demo"
    },
    {
      "id": "3",
      "name": "Event"
    },
    {
      "id": "4",
      "name": "fgvnjhfrjht"
    },
    {
      "id": "5",
      "name": "fgvnjhfrjht"
    },
    {
      "id": "6",
      "name": "fgvnjhfrjht"
    },
    {
      "id": "7",
      "name": "fgvnjhfrjht"
    },
    {
      "id": "8",
      "name": "fgvnjhfrjht"
    },
   {
      "id": "9",
      "name": "fgvnjhfrjht"
   },
   {
      "id": "10",
      "name": "fgvnjhfrjht"
   }
  ]
}

db_ads中的JSON是,

{
  "ads": [
    {
      "id": "1",
      "ads_name": "ads 1"
    },
    {
      "id": "2",
      "ads_name": "ads 2"
    }
  ]
}

我得到的JSON应该是,

{
  "ads": [
    {
      "id": "1",
      "name": "Demo Event"
    },
    {
      "id": "2",
      "name": "Demo"
    },
    {
       "id": "3",
       "name": "Event"
    },
    {
       "id": "4",
       "name": "fgvnjhfrjht"
    },
    {
       "id": "1",
       "ads_name": "ads 1"
    },
    {
       "id": "6",
       "name": "fgvnjhfrjht"
    },
    {
       "id": "7",
       "name": "fgvnjhfrjht"
    },
    {
       "id": "8",
       "name": "fgvnjhfrjht"
    },
    {
       "id": "9",
       "name": "fgvnjhfrjht"
    },
    {
       "id": "2",
       "ads_name": "ads 2"
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

首先要注意的是json可以使用以下方法解码为数组:

$aryRecords = json_decode($strRecords);
$aryAds = json_decode($strAds);

然后,因为您不只是追加,所以有必要开始循环遍历数组以在特定点插入广告:

$aryTemp = array();
$intCount = 0;
/* Make sure pointer at the start of the ads array */
reset($aryAds);

/* Start looping through your results */
foreach($aryRecords as $aryCurrentRecord) {
    $intCount++;

    /* Check if counter divisible by 5 */
    if($intCount %5 != 0) {
        $aryTemp[] = current($aryAds);
        /* Move the pointer in the ads array forward */
        next($aryAds);
    }

    $aryTemp[] = $aryCurrentRecord;
}

/* Recreate your JSON object */
$strOutput = json_encode($aryTemp);