需要以特定方式对 PHP 数组进行 json_encode

问题描述 投票:0回答:1

好吧,我有一个 PHP 数组,如下所示:

Array
(
    [0] => Array
        (
            [label] => 1
            [value] => Value example
        )
    [1] => Array
        (
            [label] => 10
            [value] => Value example 2
        )
    [...]
)

现在,如果我

json_encode()
这个数组,我得到的是:

[
    Object { label="1", value="Value example" },
    Object { label="10", value="Value example 2" },
    ...
]

但是要在 jQuery Autocomplete 中使用它,我需要数组如下所示:

[
    { label="1", value="Value example" },
    { label="10", value="Value example 2" },
    ...
]

我读了很多页但没有找到解决方案...有人可以帮忙吗?

彼得的更新:

这是我的代码:

$results = array();
foreach ($temp as $tmp) {
    $results[] = array(
        'label' => $tmp['id'],
        'value' => $tmp['it']
    );
};
echo json_encode($results);

如果它可能有用,

$temp
数组是从以下Wordpress函数生成的:

$wpdb->get_results($query, ARRAY_A);

彼得 2 更新

脚本:

jQuery(document).ready(function($){
    var temp_array = function(request, response) {
        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            type: 'POST',
            dataType: 'json',
            data: {
                'action': 'autocomplete_finder',
                'data' : request.term,
            },
            success: function(data) {
                //response(data);
                console.log(data);
            }
        });
    };
    $('#containing').autocomplete({
        source: temp_array,
        minLength: 3,
        select: function(event, ui) {
            console.log('test')
        }
    });
});

HTML:

<input id="containing" style="width: 98%">
php arrays json multidimensional-array jquery-ui-autocomplete
1个回答
1
投票

我刚刚意识到你犯了多么简单的错误

label
切换
value
:

$results = array();
foreach ($temp as $tmp) {
    $results[] = array(
        'label' => $tmp['it'],
        'value' => $tmp['id']
    );
};
echo json_encode($results);

它会起作用的

你的数组应该是这样的:

Array
(
    [0] => Array
        (
            [label] => Value example
            [value] => 1
        )
    [1] => Array
        (
            [label] => Value example 2
            [value] => 10
        )
    [...]
)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.