【问题标题】:Create a JSON array from MySQL result array for jQuery datatables从 MySQL 结果数组为 jQuery 数据表创建 JSON 数组
【发布时间】:2017-02-15 00:35:58
【问题描述】:

我有一个 mySQL 结果数组,格式如下。如果数组是“$getSessionList”

Array(

[0] =>array(

     [name] => azure

          )
[1] =>array(

     [name] => maroon

          )
)

我的目标是将这个数组转换成这种格式的 JSON 数组:

{"data": [["azure"],["maroon"]]}

我已经使用这个 PHP 代码得到了结果:

$tableData = new stdClass();
$tableData->data = array();

if (count($getSessionList) > 0) {

for ($i = 0; $i < count($getSessionList); $i ++) {
    $getSessionListRecord = $getSessionList[$i];

    $data = new stdClass(); 
    $data->name   = $getSessionListRecord['name'];


    array_push($tableData->data, $data);

     }
}

echo json_encode($tableData);

?>

以上代码产生以下结果:

{"data": [["name":"azure"],["name":"maroon"]]}

我想要这个 JSON 格式的数组:

{"data": [["azure"],["maroon"]]}

但我当前的代码给了我这个 JSON 数组:

{"data": [["name":"azure"],["name":"maroon"]]}

我不希望 JSON 数组中的键“名称”。

我怎样才能做到这一点,这里的任何帮助将不胜感激。

【问题讨论】:

    标签: php json codeigniter


    【解决方案1】:

    试试这样的:

    $tableData = new stdClass();
    $tableData->data = array();
    
    if (count($getSessionList) > 0) {
    
    for ($i = 0; $i < count($getSessionList); $i ++) {
        $getSessionListRecord = $getSessionList[$i];
    
        $data = array($getSessionListRecord['name']);
    
    
        array_push($tableData->data, $data);
    
         }
    }
    
    echo json_encode($tableData);
    
    ?>
    

    目前您正在使用此代码创建一个新的 PHP 对象

    $data = new stdClass();

    然后您将使用以下行将数据添加到键 name 中:

    $data-&gt;name = $getSessionListRecord['name'];

    通过简单地将数据放入一个空数组,然后将其推送到另一个数组中,当您转换为 JSON 时,您将没有 name 键。

    【讨论】:

    • 此解决方案完美运行。但是@Wizard 解决方案的 LOC 较少,所以我更喜欢它。
    • @echology 不用担心;有时人们会尽可能地喜欢他们的原始代码,因为这对他们来说很有意义——因此我尽可能多地保留你的代码。很高兴你成功了!
    • 我忘了说谢谢。我必须同意你按我的要求回答。每个人都喜欢速记,尤其是在编程中,我们有时不知道有预定义的“方法”,如果我们用参数调用它们会产生与我们的许多代码行相同的结果。所以在这个问题上我们是同一艘船的水手:-)
    【解决方案2】:

    试试这个:

    $tableData = array();
    $tableData['data'] = array_map(function($session) {
        // it's a separate session item inside the session_list
        return array($session['name']);
    }, $getSessionList);
    
    // any associative array converts to js-object
    // it doesn't matter is that an associative array or std-object
    echo json_encode($tableData);
    

    【讨论】:

    • 效果很好。谢谢。
    猜你喜欢
    • 2022-09-22
    • 2021-12-14
    • 2016-04-12
    • 2012-12-20
    • 1970-01-01
    • 2013-01-29
    • 2014-01-16
    • 1970-01-01
    • 2012-11-22
    相关资源
    最近更新 更多