【问题标题】:Modify array merge修改数组合并
【发布时间】:2019-12-07 00:55:01
【问题描述】:

希望我能解释一下,以便于理解。我很挣扎,所以我来这里希望能得到一些帮助:)

我正在组合/合并几个表。它似乎工作得很好,但您会注意到下面的代码行。

$records = array_merge($records, $records3);

我需要对其进行修改,使其包含“来源”。

例如:

{
    "tags": [
        {
            "id": "1",
            "name": "video",
            "cssanimate": "flipInY",
             source:{
                "mp4": "1.mp4",
                "ogg": ""
            }
        }
    ]
},

这就是它现在的显示方式。这是错误的!

{
    "tags": [
        {
            "id": "1",
            "name": "video",
            "cssanimate": "flipInY",
            "mp4": "1.mp4",
            "ogg": ""
        }
    ]
},

这是我的代码:

$result = $mysqli->query("SELECT id, username, volume, name, content, image, cssanimate, group_name FROM table_1 ORDER BY id ");
$result2 = $mysqli->query("SELECT id, username, volume, name, content, image, cssanimate, group_name FROM table_2 ORDER BY position");
$result3 = $mysqli->query("SELECT id, name, cssanimate, mp4, ogg FROM table_3 ORDER BY id ");


$records2 = array();
while ($row2 = $result2->fetch_assoc()) {
    $records2[] = array('tags' => array($row2));
}

$records3 = array();
while ($row3 = $result3->fetch_assoc()) {
    $records3[] = array('tags' => array($row3));
}

// Place "table_2" and "table_3" in every 10th position
$counter = 0;
while ($row = $result->fetch_assoc()) {

    $counter++;
    if(($counter % 10 == 0) || $counter==1 ) {
        $records = array_merge($records, $records2);
        $records = array_merge($records, $records3);
    }
    $records[] = array('tags' => array($row));
}


// Make is pretty
$json = json_encode($records, JSON_PRETTY_PRINT);


......

感谢任何帮助!

【问题讨论】:

标签: php json mysqli


【解决方案1】:

尝试为此使用内置函数会发疯。让它完全按照你的意愿去做太复杂了;我建议手动构建该数组:

$result3 = $mysqli->query("SELECT id, name, cssanimate FROM table_3 ORDER BY id ");
$result4 = $mysqli->query("SELECT mp4, ogg FROM table_3 ORDER BY id ");

...

$records4 = array();
while ($row4 = $result4->fetch_assoc()) {
    $records4[] = array('tags' => array('source' => array($row4)));
}

$merged = array_merge_recursive($records3, $records4);

【讨论】:

  • 嘿!感谢您的回复,但我收到一个错误“解析错误:语法错误,意外 '=>' (T_DOUBLE_ARROW),期待 ')'”
  • 我认为$records4[] = array('tags' => array('source' => array($row4))); 是有意的。
  • 感谢你们到目前为止的所有帮助!我收到一个错误“致命错误:调用数组中的成员函数 fetch_assoc()” - 这是由 $result = array_merge_recursive($records3, $records4);因为“$result”与while循环同名?这是更新的代码codeshare.io/219lq7
  • 是的,很抱歉这些错误。 :( 将 $result 更改为其他内容;请参阅上面的编辑。
  • @FoulFoot 谢谢!我觉得这很接近!这是完整更新的代码codeshare.io/2jEq4B,但这就是我得到的codeshare.io/5Nkwe8源代码在哪里?
猜你喜欢
  • 1970-01-01
  • 2011-02-22
  • 2013-03-20
  • 2021-01-02
  • 2019-06-09
  • 2016-07-08
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多