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

标签 php mysql json

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

db_events 的 JSON 值中,我想分别在位置 5 处添加来自 db_ads 的第一个 JSON 值,在位置 10 处添加第二个值。

我该如何实现这个。这可能吗?

来自表 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"
    }
  ]
}

最佳答案

首先要注意的是 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);

关于php - 使用 PHP 在指定位置合并 2 个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31068029/

相关文章:

php Mysql从大子树返回信息

PHP 显示为 HTML

PHP MySQL : inserting Json response values into database by iterating through loops

mysql - 将重复的行转置为mysql中的列

arrays - 序列化错误

json - 比较和更新Json数组

php - 带有 CSS 颜色的事件链接

php - 返回用户自己的 ID 的搜索查询

mysql - LOAD DATA LOCAL INFILE 未正确加载

mysql - 在 mysql 4.0 中获取 innodb 表行数的最快方法是什么?