从多维数组中提取值并将其放入逗号分隔的字符串中
我有一个看起来像这样的数组,
Array
(
[1] => Array
(
[name] => Zeze
[city] => Denver,
[state] => Colorado,
[country] => United States
[user_id] => 1
[cars] => Array
(
[140] => Array
(
[cars_name] => BMW
)
[162] => Array
(
[cars_name] => Mazda
)
)
)
[8] => Array
(
[name] => Lex
[city] => Schwelm,
[state] => North Rhine-Westphalia,
[country] => Germany
[user_id] => 5
[cars] => Array
(
[140] => Array
(
[cars_name] => Mercedes
)
[162] => Array
(
[cars_name] => Audi
)
)
)
)
我需要从 user_id
中提取值并将其放入逗号分隔的字符串中。
对于上面的数组,我想得到:
1,5
我有点困惑如何使用 foreach
循环这个数组,然后如何创建字符串?或者有更好的方法吗?
I have an array that looks like this
Array
(
[1] => Array
(
[name] => Zeze
[city] => Denver,
[state] => Colorado,
[country] => United States
[user_id] => 1
[cars] => Array
(
[140] => Array
(
[cars_name] => BMW
)
[162] => Array
(
[cars_name] => Mazda
)
)
)
[8] => Array
(
[name] => Lex
[city] => Schwelm,
[state] => North Rhine-Westphalia,
[country] => Germany
[user_id] => 5
[cars] => Array
(
[140] => Array
(
[cars_name] => Mercedes
)
[162] => Array
(
[cars_name] => Audi
)
)
)
)
I need to extract the value from user_id
and put it in a comma separated string.
For the above array, I would like to get:
1,5
I'm a bit confused how to loop this array with foreach
and then how would I create the string? Or is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设您的数组名为
$users
并且$list
是输出。This is assuming your array is named
$users
and$list
is the output.您可以结合使用
array_map
和内爆
:You can use a combination of
array_map
andimplode
:使用 foreach 循环迭代多维数组中的每个项目,并将该项目视为普通数组。然后将 user_id 值推入另一个数组,并用逗号将其内爆,使其以逗号分隔。
Iterate over each item in the multimensional array with a foreach loop, and treat the item as a normal array. Then push the user_id value into another array and implode it with a comma to make it comma separated.
这将是最简单的方法:
echo implode(",", array_column($myArray, "user_id"));
This will be the most easier method:
echo implode(",", array_column($myArray, "user_id"));