如何从一种数组项目中创建一个字符串?(How to make a string from one kind of array items?)

编程入门 行业动态 更新时间:2024-10-27 21:14:39
如何从一种数组项目中创建一个字符串?(How to make a string from one kind of array items?)

我有一个这样的数组:

$results = $stmt->fetchAll(PDO::FETCH_ASSOC); /* Array ( [0] => Array ( [id] => 191 [type] => 3 [table_code] => 15 ) [1] => Array ( [id] => 192 [type] => 3 [table_code] => 15 ) [2] => Array ( [id] => 194 [type] => 3 [table_code] => 15 ) ) */

我试图用逗号分隔符来创建一个包含所有ID的字符串。 像这样的东西:

echo $ExpectedOutput; // 193, 192, 194

我怎样才能做到这一点?


这是我迄今为止所尝试的:

foreach($results as $item) { $ExpectedOutput = $item['id']; }

但总是有一个,在该字符串的末尾。

I have an array like this:

$results = $stmt->fetchAll(PDO::FETCH_ASSOC); /* Array ( [0] => Array ( [id] => 191 [type] => 3 [table_code] => 15 ) [1] => Array ( [id] => 192 [type] => 3 [table_code] => 15 ) [2] => Array ( [id] => 194 [type] => 3 [table_code] => 15 ) ) */

And I'm trying to make a string of all IDs with a comma separator. Something like this:

echo $ExpectedOutput; // 193, 192, 194

How can I do that?


Here is what I've tried so far:

foreach($results as $item) { $ExpectedOutput = $item['id']; }

But always there is a , in the end of that string.

最满意答案

你可以使用implode和array_column来做到这array_column 。

Array Column从该数组的所有id中生成一个数组,然后implode使用分隔符从该数组中创建一个字符串。 正如你想使用的, 。

echo implode(", ", array_column($results, "id")); //193, 192, 194

You can do this using the implode and array_column.

Array Column makes an array from all the id of that array, and after that implode makes a string from that array with a delimiter. As you want to use ,.

echo implode(", ", array_column($results, "id")); //193, 192, 194

更多推荐

本文发布于:2023-07-26 19:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1280295.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   创建一个   项目   items

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!