[英]How to fetch multiple row value which contains multiple value separated by comma into a single array in php using pdo mysql
I have a database table name books.我有一个数据库表名书籍。 Now I need to fetch value from multiple row values (column name position) which contains multiple value separated by comma.
现在我需要从包含多个用逗号分隔的值的多行值(列名位置)中获取值。 Now I need to fetch values from multiple rows into an array using pdo php.
现在我需要使用 pdo php 将多行中的值提取到一个数组中。
<?php
require_once "includes\config.php";
$sql = 'SELECT * FROM books WHERE shelf_no=2';
$stmt = $db->prepare($sql);
$stmt->execute();
$row = $stmt->fetchALl(PDO::FETCH_ASSOC);
$d = array();
foreach ($row as $value) {
$d[] = explode(",",$value['position']);
}
print_r($d);
?>
and the result is结果是
Array (
[0] => Array (
[0] => b1
[1] => b2
)
[1] => Array (
[0] => a2
[1] => a3
)
)
But I need all values in a single array, like this:但我需要一个数组中的所有值,如下所示:
Array ( [0] => b1 [1] => b2 [2] => a2 [3] => a3 )
You are exploding it (creating a new array) and then adding that array to another array.您正在分解它(创建一个新数组),然后将该数组添加到另一个数组中。
You could run through each value in the exploded string and add them:您可以遍历分解字符串中的每个值并添加它们:
<?php
require_once "includes\config.php";
$sql = 'SELECT * FROM books WHERE shelf_no=2';
$stmt = $db->prepare($sql);
$stmt->execute();
$row = $stmt->fetchALl(PDO::FETCH_ASSOC);
$d = array();
foreach ($row as $value) {
$temp = explode(",",$value['position']);
foreach($temp as $pos){
array_push($d, trim($pos));
}
}
print_r($d);
?>
If there are duplicates they will show though.如果有重复,他们会显示。
You can also replace your你也可以更换你的
$d[] = explode(",",$value['position']);
with和
array_merge($d, explode(',', $value['position']));
That will make one array rather than an array of arrays.这将创建一个数组而不是一组数组。 More info on array_merge at php.net.
php.net 上有关array_merge 的更多信息。
A lot of PHP functions are more performant than the equivalent written in PHP.许多 PHP 函数的性能比用 PHP 编写的等效函数要高。 Ie this may be faster than a nested
foreach
loop.即这可能比嵌套的
foreach
循环更快。 As always, if this is important to you, time both ways.与往常一样,如果这对您很重要,请双向计时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.