【问题标题】:need to json_encode a PHP array in a particular way需要以特定方式对 PHP 数组进行 json_encode
【发布时间】:2014-11-19 13:24:14
【问题描述】:

好的,我有一个看起来像这样的 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%">

【问题讨论】:

  • 这不是json_encode 输出。有 : 字符而不是 = 并且没有“对象”。 proofjson_encode 也非常适合 jquery 自动完成。 = 也不是正确的 JSON。请向我们展示您的代码。
  • @Peter 我已经为你更新了问题。
  • 看起来不错。你能告诉我“json_encode”的实际结果吗?我猜你从浏览器控制台复制粘贴的数据不是你发送到浏览器的原始文本。我认为您的 PHP 代码很好,javascript 方面存在一些问题
  • 是的,我已经从控制台复制粘贴了代码。从浏览器输出中获取的实际结果似乎是 jQuery Autocomplete 需要的正确格式。那为什么自动完成功能不起作用? [{"label":"1","value":"Value example"},{"label":"10","value":"Value example 2"},...]
  • 确保您的选择器$('#whatever') 正确。这个微不足道的错误通常很难找到。你也能展示一下如何在 js 中启动自动完成功能吗?

标签: arrays json multidimensional-array jquery-ui-autocomplete


【解决方案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
        )
    [...]
)

【讨论】:

  • 我试过了,没有区别...为什么切换它们会有任何区别?
  • @Mariano 因为它给你提示label而不是value
  • 天啊...多么愚蠢的错误...现在可以正常工作了(自从第一次发表评论以来,我几乎没有刷新过浏览器)...非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
相关资源
最近更新 更多