phparraysjsonmultidimensional-arrayjquery-ui-autocomplete

need to json_encode a PHP array in a particular way


Ok, what i have is a PHP array that looks like this:

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

Now, if i json_encode() this array, what i get is:

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

But to use it in jQuery Autocomplete i need the array to be like this:

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

I've read tons of pages without finding a solution...can someone help?

UPDATE FOR PETER:

Here's my code:

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

If it may be useful, $temp array is generated from the following Wordpress function:

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

UPDATE FOR PETER 2

SCRIPT:

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%">

Solution

  • I just realized what simple mistake you did

    Switch label with value:

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

    and it will works

    your array should look like this:

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