Php 如何从一种数组项生成字符串?

Php 如何从一种数组项生成字符串?,php,arrays,string,Php,Arrays,String,我有这样一个数组: $results = $stmt->fetchAll(PDO::FETCH_ASSOC); /* Array ( [0] => Array ( [id] => 191 [type] => 3 [table_code] => 15 ) [1] => Array ( [id] =&g

我有这样一个数组:

$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
        )
)
*/
echo $ExpectedOutput; // 193, 192, 194
我试图用逗号分隔符将所有ID组成一个字符串。大概是这样的:

$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
        )
)
*/
echo $ExpectedOutput; // 193, 192, 194
我该怎么做


以下是我到目前为止所做的尝试:

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

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

您可以使用
内爆
数组列
来执行此操作

数组列从该数组的所有id生成一个数组,然后内爆从该数组生成一个带分隔符的字符串。如果要使用

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

您可以使用
内爆
阵列列
来执行此操作

数组列从该数组的所有id生成一个数组,然后内爆从该数组生成一个带分隔符的字符串。如果要使用

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

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

echo $ExpectedOutput;  //193, 192, 194
试试这个

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

echo $ExpectedOutput;  //193, 192, 194

在代码中再添加一行,以便使用substr函数删除最后一个逗号

if($expectedOutput != '')  
  $expectedOutput  = substr($expectedOutput,0,-1);  
echo $expectedOutput; // 191, 192, 194

在代码中再添加一行,以便使用substr函数删除最后一个逗号

if($expectedOutput != '')  
  $expectedOutput  = substr($expectedOutput,0,-1);  
echo $expectedOutput; // 191, 192, 194

使用
echo内爆(“,”,array_column($arr,“id”))
使用
echo内爆(“,”,array_column($arr,“id”))
这不是标准,但应该可以工作。谢谢你+1可能是。。。使用内爆和数组_列函数是最好的方法。从@Frayne Konok的回答来看,这不是标准答案,但应该有效。谢谢你+1可能是。。。使用内爆和数组_列函数是最好的方法。来自@Frayne Konok的答案