Reputation: 431
I have a 2D array , which holds the result of a mysql query. here is my code
$res=$ $this->dbconnection->Query($Query);
$query_result= array();
while($colRow=mysqli_fetch_array($res))
{
$query_result[]= $colRow;
}
Now i want 1D array which contains all rows under a particular column in $query_result.
For example, the database table contains the fields Name and ID,I know , $query_result[]= $colRow['Name']
will give query results into ID. But I need all rows under Name and Id separately , such as $name= $query_result['Name']
,$Id= $query_result['ID']
.
Is there any easy way to accomplish this?
Upvotes: 3
Views: 2439
Reputation: 641
Converting array of rows into array of columns:
<?php
$arr2dm = [['key1' => 'val11', 'key2' => 'val21'], ['key1' => 'val12', 'key2' => 'val22']];
foreach ($arr2dm as $arr) {
foreach ($arr as $k => $v) {
$res[$k][] = $v;
}
}
print_r($res);
http://sandbox.onlinephpfunctions.com/code/514050d07f9ed599e010ccd11e51fc18e39647fa
Upvotes: 0
Reputation: 20882
Since PHP 5.5.0 you can use...
$myfield_arr = array_column($query_result, 'myfield_name');
... to isolate a column from a two dimensional array.
See http://php.net/manual/en/function.array-column.php
Upvotes: 6
Reputation: 1276
After clarifying question in comments with you, solution is:
while($colRow=mysqli_fetch_array($res)){
foreach ($colRow as $key => $value) {
if(!isset($query_result[$key])) $query_result[$key]=array();
$query_result[$key][] = $value;
}
}
Upvotes: 1
Reputation:
Please try maybe
$res=$ $this->dbconnection->Query($Query);
$query_result= array();
while($colRow=mysqli_fetch_array($res))
{
if (empty($query_result))
$query_result = $colRow;
else
{
foreach ($colRow as $key=> $val)
$query_result[$key][] = $val;
}
}
Upvotes: 1
Reputation: 492
Use something like this:
foreach ($rows as $key => $value) {
$$key = $value;
}
Upvotes: 0