dragon8837 2015-02-25 22:28
浏览 24

json_encode不适用于行名数组

I realize I'm using mysql and not mysqli. I need to solve this issue before I can update the existing code. I currently querying data as well as the table row names from the database via php. I cant figure out why I am not receiving a response when I run the json_encode. Can someone please help me out?

My desired output in JSON format is as follows..

{ "projects" : [
  {
    "title":"title 1",
    "image":"Image1",
    "subtitle":"subtitle 1",
    "about":"Blah Blah Blah"
  },
  {
    "title":"title 2",
    "image":"Image2",
    "subtitle":"subtitle 2",
    "about":"Blah Blah Blah"
  }
]}

Right now my code looks like this..

// 1) Connect to mysql database
    $con = mysql_connect($host,$user,$pass);
    $dbs = mysql_select_db($databaseName, $con);

  // 2) Query database for data
  $result = mysql_query("SELECT * FROM $tableName");   
    if (mysql_num_rows($result) > 0) 
    {
      $numFields = mysql_num_fields($result);
      $fields = array();
      $i = 0;
      while ($i < $numFields) {
        $fieldInfo = mysql_fetch_field($result, $i);
        $fields[] = $fieldInfo->name;
        $i++;
      }

      $userInfo = array();
      $userInfo["projects"] = array();
      while($row = mysql_fetch_row($result)) {

          $project = array();
          $i = 0;
          while ($i < mysql_num_fields($result)) {
            $project[$fields[$i]] = $row[$i];
            $i++;
          }
          $userInfo["projects"][] = $project;
      }

      //echo '<pre>';
      //    print_r($userInfo);
      //echo '</pre>';

      echo json_encode($userInfo["projects"]);
    }
    else 
    { 
        echo ( "No rows found!" );
    }

When I execute the echo '<pre>' above (currently commented out) I get the following result. However when I remove this and try return the data as JSON I get no result. Could someone please help me out.

Array
(
    [projects] => Array
        (
            [0] => Array
                (
                    [title] => title
                    [subtitle] => subtitle 1
                    [about] => Blah Blah Blah
                    [image] => Image1
                )

            [1] => Array
                (
                    [title] => title 2

                    [subtitle] => subtitle 2

                    [about] => Blah Blah Blah
                    [image] => Image2
                )
         )
)
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 软件测试决策法疑问求解答
    • ¥15 win11 23H2删除推荐的项目,支持注册表等
    • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
    • ¥15 qt6.6.3 基于百度云的语音识别 不会改
    • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
    • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
    • ¥15 lingo18勾选global solver求解使用的算法
    • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
    • ¥20 测距传感器数据手册i2c