Json 数组到带有 php 的选择框中

Json array into select box with php

本文关键字:选择 php 数组 Json      更新时间:2023-09-26

我希望有人可以帮助我解决这个问题。我想要的是一个选择框,它是从 json 文件中填充的。问题是我有一个奇怪的json文件,我不知道它是数组还是对象。

以下是它的样子:

{
"Id": 4,
"Name": "Testing Demo",
"OpeningHours": [
    {
        "Name": "Monday",
        "Hours": "Kl. 09:30:00 - 21:00:00"
    }
],
"Address": {
    "Street": "Johnson road",
    "StreetNumber": "5",
    "Town": "London"
},
"Phone1": "4123213414",
"Phone2": null,
"Documents": null,
"Messages": [
    {
        "Title": "We are on the way",
        "Body": "fine",
        "Created": "01-02-2014"
    },
    {
        "Title": "Get the stuff",
        "Body": "To be ready",
        "Created": "01-01-2014"
    }
],
"Employees": [
    {
        "Name": "John Hood",
        "Description": "officer",
        "ProfileImageUrl": "http://grfx.cstv.com/photos/schools/kty/sports/m-baskbl/auto_headshot/9265204.jpeg"
    },
    {
        "Name": "John hood 2",
        "Description": "athletic",
        "ProfileImageUrl": "http://grfx.cstv.com/photos/schools/kty/sports/m-baskbl/auto_headshot/9265204.jpeg"
    }
]
}

我将如何显示 ID 和名称的值?

这段代码不起作用,我不知道我是否正确地这样做了。

(function($) {
$(document).ready(function() {
    $('<tr class="form-field form-required"></tr>').append(
        $('<th scope="row">New field</th>')
    ).append(
        $('<td></td>').append(
            $('<select id="release-list"></select>')
        ).append(
            $('<p>Explanation about your new field</p>')
        )
    ).insertAfter('#wpbody-content table tr:eq(2)');


});
 $.getJSON('../../cache/path.json', function(data) {
    var select = $('#release-list');
    $.each(data, function(key, val){
        $('<option/>').attr('value', val[key]["Id"]).html('value' + val[key]["Name"]).appendTo(select);
    });
    });
    })(jQuery);

您可以使用 JSON.parse() 将数据从 JSON 转换为数组

http://www.dyn-web.com/tutorials/php-js/json/parse.php

例:

var data = '{"first":[1,2,3],"second":[4,5,6]}';
var jsonData = JSON.parse(data);
alert(jsonData.first[1]);
alert(jsonData.second);