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.
<?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.
A lot of PHP functions are more performant than the equivalent written in PHP. Ie this may be faster than a nested foreach
loop. As always, if this is important to you, time both ways.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.