简体   繁体   English

从PHP到javascript正确格式化json?

[英]Get correctly formatted json from php to javascript?

I have a database with a tabled named options. 我有一个带有tabled命名选项的数据库。 In this table I have 3 fields 在这张表中,我有3个字段

  1. id of type int autoincrement int自动增量类型的id
  2. option_name of type varchar varchar类型的option_name
  3. option_value of type varchar varchar类型的option_value

Assume I have the following to records inserted already 假设我已将以下内容添加到记录中

  1. '1','homepage_title','Home' '1', 'homepage_title', '家'
  2. '2','index_page_title','Index Page' '2','index_page_title','索引页'

I have a php script as follows 我有一个PHP脚本如下

<?php
header("Access-Control-Allow-Origin: *");
//set timezone becuase some servers are jsut wrong
define('TIMEZONE', 'Europe/Athens');
date_default_timezone_set(TIMEZONE);

//Connect & Select Database
mysql_connect("somehost","simeuser","somepass") or die("could not connect server");
mysql_select_db("somedbdb") or die("could not connect database");

function getOptions(){
    $sqldata = mysql_query("SELECT * FROM `options`");
    $rows = array();
    while($r = mysql_fetch_array($sqldata)) {
        $rows[$r['option_name']][$r['option_value']][]=$r['option_value'];
    }

    echo json_encode($rows);
}
getOptions();
?>

It works because the script returns something like this 它起作用,因为脚本返回这样的东西

{"homepage_title":{"Home":["Home"]},"index_page_title":{"index page":["index page"]}}

I am sure the line that is incorrect is this one 我确定不正确的行就是这一行

$rows[$r['option_name']][$r['option_value']][]=$r['option_value'];

I just can't figure out what I need to fix. 我只是无法弄清楚我需要修复什么。 My intensions is to call javascript as follows 我的意思是调用javascript如下

$.get("http://localhost/test-app/get_app_settings.php",function(data){
    var json = JSON.parse(data);
    console.log(JSON.stringify(json));
    alert("homepage title was "+json['homepage_title']);
    alert("index page title was "+json['index_page_title']);
});

I get Object object instead of Homepage which I expected in homepage_title and Index page which I expect in index_page_title. 我得到了Object对象而不是我在homepage_title中预期的主页以及我期望在index_page_title中的索引页面。

I am sure it something really stupid but I just can see it. 我确信它真的很蠢,但我只能看到它。

What's your intention of doing this? 你打算这样做的意图是什么?

$rows[$r['option_name']][$r['option_value']][]=$r['option_value'];

Maybe you want just this? 也许你想要这个?

$rows[$r['option_name']]=$r['option_value']; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM