【问题标题】:How can I display only values in json instead of key:value pairs?如何仅显示 json 中的值而不是键:值对?
【发布时间】:2016-01-17 14:50:27
【问题描述】:

我有我的 mysqli 查询:

$fetchTransactions = "SELECT * FROM transaction WHERE client_id = '$client_id'";
$result = $mysqli->query($fetchTransactions);
$data = array();    
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );

它返回 json 为:

[{"transaction_id":"1","client_id":"2","total_price":"100.70","creation_date":"2015-10-18 03:00:00","unique_hash":"ABCDEF"},
{"transaction_id":"2","client_id":"2","total_price":"88.20","creation_date":"2015-10-18 04:00:00","unique_hash":"GHIJK"}]

而不是这个,我想在这里展示一个表格中的数据:

{
  "data": [
    [
      "1",
      "2",
      "100.70",
      "2015-10-18 03:00:00",
      "ABCDEF"
    ],
    [
      "2",
      "2",
      "88.20",
      "2015-10-18 03:00:00",
      "GHIJK"
    ],

因为我需要这种 json 格式来提供从这里获取的数据表:https://datatables.net/examples/data_sources/ajax.html

你能帮我解决这个问题吗?

【问题讨论】:

    标签: php jquery json mysqli


    【解决方案1】:

    不要将$data 转换为json,而是循环遍历它。 array_values 函数将从关联数组中提取所有数组值。

    <?php 
     $newarray = array();
     foreach($data as $d){
      // save array values to $newarray
      $newarray['data'][] = array_values($d);
     }
    
    $json_newarray = json_encode($newarray);
    
    echo print_r($json_newarray, true);
    
    ?>
    

    【讨论】:

      【解决方案2】:

      使用array_map 遍历行值并使用array_values 忽略键(列名),您可以执行以下操作:

      echo json_encode( array( 'data' => array_map('array_values', $data) ) );
      

      【讨论】:

        猜你喜欢
        • 2018-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-18
        • 1970-01-01
        • 2020-03-06
        相关资源
        最近更新 更多