Ariana
Ariana

Reputation: 755

PHP/jQuery - How To Convert A Multidimensional PHP Array To JSON String?

As the title states, I'm trying to use Bootstrap's Typeahead.js, and it requires a JSON string like this

 var subjects = ['PHP', 'MySQL', 'SQL', 'PostgreSQL', 'HTML', 'CSS', 'HTML5', 'CSS3', 'JSON'];  

But I have a multidimensional array that upon doing json_encode returns the following

[{"username":"Test1"},{"username":"Test2"},{"username":"Test3"},{"username":"Test4"},{"username":"Test5"},{"username":"Test6"}]

Typeahead.js throws out errors when I try using this array.

How would I convert the multidimensional to look like the example one?

Original PHP Array

Array
(
[0] => Array
    (
        [username] => Test1
    )

[1] => Array
    (
        [username] => Test2
    )

[2] => Array
    (
        [username] => Test3
    )

[3] => Array
    (
        [username] => Test4
    )

[4] => Array
    (
        [username] => Test5
    )

[5] => Array
    (
        [username] => Test6
    )

)

Desired outcome would be

var subjects = ['Test1', 'Test2', 'Test3', 'Test4', 'Test5', 'Test6'];

Upvotes: 4

Views: 1968

Answers (2)

Mark Reed
Mark Reed

Reputation: 95242

So, first you need to create a PHP array that has what you want in it. Then the JSON encoding process will automatically produce the correct result. You should accept Barmar's answer:

$flat_array = array_map(function($x) { return $x['username']; }, $array_of_arrays);

These three forms are just different syntactic conventions for representing the same thing - an array of six strings.

PHP Array literal:

Array( 'Test1', 'Test2', 'Test3', 'Test4', 'Test5', 'Test6' );

PHP print_r output:

Array
(
    [0] => Test1
    [1] => Test2
    [2] => Test3
    [3] => Test4
    [4] => Test5
    [5] => Test6
)

JSON:

[ "Test1", "Test2", "Test3", "Test4", "Test5", "Test6" ]

That last one is of course also the array literal syntax for JavaScript (since JSON is just a standardized subset of Javascript's literal syntax). It also happens to work in a number of other languages, including Perl, Python, Ruby, Haskell, Clojure, Erlang ...

But the point is, the structure is what you care about. JSON is just syntax, easily converted to and from.

Upvotes: 0

Barmar
Barmar

Reputation: 780724

Your original array is 2-dimensional. You need to get the elements of each sub-array, and then convert that to JSON:

echo json_encode(array_map(function($x) { return $x['username']; }, $original_array));

Alternatively, you could fix whatever code is creating the original array in the first place. Why is it putting an associative array in each element, instead of just the usernames themselves? There's not much point to having them be associative arrays if they only have one element, always with the same key.

Upvotes: 5

Related Questions