【问题标题】:Convert JSON arrays to JSON format将 JSON 数组转换为 JSON 格式
【发布时间】:2018-03-11 23:14:48
【问题描述】:

我在将 JSON 数组转换为 JSON 格式数据时遇到问题,目前我正在以这种格式获取输出:

但我想以这种格式输出:

这是我正在使用的代码:

    <?php

// Create connection
$conn = mysqli_connect("127.0.0.1","root","", "testapp");

$sql = "SELECT * FROM timetable";

$result = mysqli_query($conn, $sql);

    $rows = array();
    while ($row = mysqli_fetch_assoc($result)) {

            $rows[] = $row; 

    }

echo json_encode($rows);


echo "<pre>";
print_r($rows);
echo "</pre>"; 

?>

【问题讨论】:

  • 两张截图中的数据结构似乎完全不相关。预期的 JSON 最终结果包含像 NameMajor 这样的键,但在有效负载(数组)中没有任何这些键出现......你能联系一下吗?

标签: php mysql arrays json mysqli


【解决方案1】:
Use the below mentioned step.

print_r(json_encode($rows));


// Example

<?php
$val = (array('0'=>array('id'=>'2',
                        'name'=>'kmg'),
             '1'=>array('id'=>'3',
                       'name'=>'kumar')));

print_r($val);
echo '<br>';
echo '<br>';
print_r(json_encode($val));

?>

// Result

Array ( [0] => Array ( [id] => 2 [name] => kmg ) [1] => Array ( [id] => 3 [name] => kumar ) ) 

[{"id":"2","name":"kmg"},{"id":"3","name":"kumar"}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多