我正在尝试遍历从select * from table_name where id in (select min(id) from table_name group by c, s);
结果获得的数组,以便从所有结果中创建一个字符串。
Array看起来像这样:
preg_match_all
我的代码:
print_r($matches[0]);
Array
(
[0] => Array
(
[0] => 8147
[1] => 3
)
[1] => Array
(
[0] => 8204
[1] => 20
)
)
我希望得到$found = count($matches[0]);
for ($i = 0; $i <= $found; $i++) {
$string = $matches[0][$i];
}
的结果:$string
如何使用循环在字符串变量中将8147, 8204
附加到$matches[0][0]
等?
答案 0 :(得分:2)
你可以这样做吗
$string = "";
foreach($matches[0] as $value) {
$string .= $value[0].", ";
}
$string = rtrim(", ",$string);
答案 1 :(得分:1)
尝试以下代码。循环遍历数组并获取值
$arr =Array
(
0 => Array
(
0 => 8147,
1 => 3
),
1 => Array
(
0 => 8204,
1 => 20
)
);
$match_array = array();
foreach($arr as $key=>$value)
{
$match_array[] = $value[0];
}
$str = implode(",",$match_array);
echo $str;
或者只是使用array_column将特定列作为数组获取然后使用implode
$arr =Array
(
0 => Array
(
0 => 8147,
1 => 3
),
1 => Array
(
0 => 8204,
1 => 20
)
);
$match_array = array_column($arr,0);
$str = implode(",",$match_array);
echo $str;
答案 2 :(得分:1)
使用php5.5及更多版本,您可以使用array_column
+ implode
:
echo implode(', ', array_column($matches, 0));
答案 3 :(得分:1)
您可以使用array_column
,无需循环遍历数组
$result = join(',', array_column($arr, 0));