PHP / jQuery的 - 如何转换多维数组PHP要JSON字符串? [英] PHP/jQuery - How To Convert A Multidimensional PHP Array To JSON String?

查看:188
本文介绍了PHP / jQuery的 - 如何转换多维数组PHP要JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题状态,我试图用引导的Typeahead.js,它需要一个JSON字符串像这样

  VAR科目= ['PHP','MySQL的','SQL','PostgreSQL的,HTML,CSS,HTML5,CSS3','JSON '];

不过,我有一个多维数组,在做json_en code返回以下

<$p$p><$c$c>[{\"username\":\"Test1\"},{\"username\":\"Test2\"},{\"username\":\"Test3\"},{\"username\":\"Test4\"},{\"username\":\"Test5\"},{\"username\":\"Test6\"}]

Typeahead.js当我尝试使用这个数组抛出错误。

我将如何转换多维看起来像的例子吗?

原始PHP阵列

 阵列

[0] =&GT;排列
    (
        [用户名] =&GT;测试1
    )[1] =&GT;排列
    (
        [用户名] =&GT; TEST2
    )[2] =&GT;排列
    (
        [用户名] =&GT; TEST3
    )[3] =&GT;排列
    (
        [用户名] =&GT; TEST4
    )[4] =&GT;排列
    (
        [用户名] =&GT; TEST5
    )[5] =&GT;排列
    (
        [用户名] =&GT; TEST6
    ))理想的结果是变种受试者= ['测试1','的Test2','Test3的','TEST4','TEST5','TEST6'];


解决方案

您原来的数组是二维的。你需要得到每个子数组的元素,然后将其转换成JSON:

 回声json_en code(array_map(函数($ X){返回$ x [用户名];} $ original_array));

另外,你可以解决什么code是创造摆在首位原始数组。为什么把每个元素的关联数组,而不是只是自己的用户名?没有太多的点让他们成为关联数组,如果他们只使用相同的密钥有一个元素,始终。

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'];

解决方案

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.

这篇关于PHP / jQuery的 - 如何转换多维数组PHP要JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆