【问题标题】:Convert results from Sql to Json [closed]将结果从 Sql 转换为 Json [关闭]
【发布时间】:2012-09-07 01:20:18
【问题描述】:

我有这个代码 php

$query2 = "SELECT * FROM hosts where cod='$stream'";
    $result2=mysql_query($query2);
    while ($row2=mysql_fetch_array($result2)) 
    {
$audio=$row2['audio'];
$def=$row2['def'];
$hosty=$row2['host'];   
    }

我如何以这种格式将结果转换为 json:

var sources = {"english":{"360":["bayfiles","filebox","zalaa","cramit"],"720":["cramit","180upload"]},"portugues":{"1080p":["zalaa","cramit"],"720":["cramit","180upload"]}}

有可能吗?

谢谢

【问题讨论】:

标签: php sql json


【解决方案1】:

如果要创建包含所有查询的输出数组,应使用辅助数组来获取每一行。

 $arrayAux=array();
 $query2 = "SELECT * FROM hosts where cod='$stream'";
    $result2=mysql_query($query2);
    while ($row2=mysql_fetch_array($result2,MYSQL_ASSOC)) 
    {
        $audio=$row2['audio'];
        $def=$row2['def'];
        $hosty=$row2['host'];  
        push_array(array("audio"=>$audio,"def"=>$def,"host"=>$hosty)); 
    }
  print(json_encode($arrayAux));

PS:我不明白你是想删除所有查询还是只应用一个。 如果只有一个:

  1. 消除 arrayAux。
  2. 消除while。
  3. 直接创建print (json_encode (mysql_fetch_array ($ query2, MYSQL_ASSOC)));

【讨论】:

  • 我的解决方案 $query2 = "SELECT * FROM hosts where cod='$stream'"; $result2=mysql_query($query2); while ($row=mysql_fetch_assoc($result2)) { $audio = $row['audio']; $def=$row['def']; $hosty=$row['host']; $players[$audio][$def][] = array($hosty, ); } $data = ($players); $json = json_encode($data);谢谢大家
【解决方案2】:

您可以使用 PHP 函数 json_encode() 并将其传递到与您想要的格式匹配的数组中。

【讨论】:

    【解决方案3】:

    使用json_encode():

    echo json_encode($arr);
    

    【讨论】:

      【解决方案4】:

      是的,这可以通过使用 PHP 的 json_encode() 函数来实现。

      json_encode — 返回值的 JSON 表示形式

      但是,为了获得多维对象,您可能需要执行更多查询,或者可能对从第一个查询中获得的某些值进行迭代。然后,您将在多维 PHP 数组中构建数据并在整个对象上执行 json_encode() 函数。

      $arr = array(
        'a' => 1, 
        'b' => 2, 
        'c' => array(
          'd'=>3,
          'e'=>4
        )
      );
      
      echo json_encode($arr);
      
      
      {
        "a":1,
        "b":2,
        "c":{ 'd':3,"e":4}
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-26
        • 1970-01-01
        • 2011-05-30
        • 2023-03-25
        相关资源
        最近更新 更多