如何从一种数组项目中创建一个字符串?(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, 194How 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, 194You 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更多推荐
发布评论