php mysqli result into an array not working as expected - php

I have a php /mysqli query and I want to populate an array with the results:
$query3 ="SELECT * FROM conditions";
$results = array();
if ($result = mysqli_query($conn, $query3)){
while($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
}
print_r($results);
Something is wrong here -its making arrays within arrays I think. (to be honest I am confused by this result)
How do I do this correctly!
Array (
[0] => Array ( [condition_id] => 1 [condition_name] => Epilepsy )
[1] => Array ( [condition_id] => 2 [condition_name] => ASD )
[2] => Array ( [condition_id] => 3 [condition_name] => BESD )
[3] => Array ( [condition_id] => 4 [condition_name] => HI )
[4] => Array ( [condition_id] => 5 [condition_name] => Medical )
[5] => Array ( ...
Thanks for all the help - now how should I create what I actually want which is one array with key=>value like this:
array (1=>epilepsy, 2=>ASd...) - the numbers refer to the primary key.
How do I populate an array from this query please?

Change your code as below :
while($row = mysqli_fetch_assoc($result))
{
$results[$row['condition_id']] = $row['condition_name'];
}

Move to PDO, Luke.
$results = $pdo->query("SELECT FROM conditions")->fetchAll(PDO::FETCH_KEY_PAIR);
print_r($results);
Whoops! Is that all the code?

Related

Specific value in an array does not work

I have a question about my array. How can I get only data of milestone in my milestone array?
I have a query which is a prefixed array. I get data of milestones and milestonefases (this is milestone parts).
This is my code:
$stones_fases = array();
while ($row = $db->fetchassoc($result)){
$milestonefase = array();
$milestone = array();
foreach ($row as $mkey => $mvalue){
$milestone[$mkey] = $mvalue;
foreach ($row as $fkey => $fvalue){
$milestonefase[$fkey] = $fvalue;
}
}
if (!isset($stones_fases[$milestone['milestone_id']])){
$stones_fases[$milestone['milestone_id']] = $milestone; //['client']['milestone_verkocht_id']
}
$stones_fases[$milestone['milestone_id']][$milestonefase['milestonefase_id']] = $milestonefase['milestonefase_titel'];
}
I get this:
Array
(
[int] => Array
(
[milestone_id] => int
[milestone_titel] => string
[client] => string
[milestone_verkocht_id] => 99
[milestonefase_id] => 10
[milestonefase_titel] => string
[milestonefase_milestone_id] => 6
[10] => string
[11] => string
)
)
But I want this:
Array
(
[int] => Array
(
[milestone_titel] => string
[client] => string
[milestone_verkocht_id] => int
[10] => string
[11] => string
)
)
My query is this:
$project = $_COOKIE['project'];
$query = " SELECT
a.id AS `milestone_id`,
a.titel AS `milestone_titel`,
a.client AS `client`,
a.verkocht_id AS `milestone_verkocht_id`,
b.id AS `milestonefase_id`,
b.titel AS `milestonefase_titel`,
b.milestone_id AS `milestonefase_milestone_id`
FROM `milestones` a
INNER JOIN `milestone_parts` b ON a.id=b.milestone_id
WHERE a.verkocht_id = '{$project}' ";
$result= $db->query($dbh, $query);
I solved my own problem!
If i do this:
while ($row = $db->fetchassoc($result)){
$stones_fases[$row['milestone_id']]['milestone_titel'] = $row['milestone_titel'];
$stones_fases[$row['milestone_id']]['milestone_client'] = $row['client'];
$stones_fases[$row['milestone_id']]['milestonesfases'][$row['milestonefase_id']] = $row['milestonefase_titel'];
}
I get what i expected:
Array
(
[2] => Array
(
[milestone_titel] => Beheer opleveren
[milestone_client] => stackoverflow
[milestonesfases] => Array
(
[1] => Menu bouwen
[2] => Pagina beheer CMS
[3] => Projecten CMS
[4] => Portfolio
[5] => Footer inbouwen
)
)
)
Look at that bunch of code what I wrote a day ago.
Do you see that nonsens of code what I wrote?
Take a look at my code which I wrote 1 minute ago!
I was struggling this for 3 days and now I solved my own problem!

PHP - Array does not turn into two-dimensional array

I need to make my array better.
I am getting data from database and i have milestones and milestone_parts. i want two-dimensional array. I need data of milestones in the first dimension and milestone_parts in the second dimension.
With this code:
$query = "
SELECT
a.id AS `milestone_id`,
a.titel AS `milestone_titel`,
a.client AS `client`,
a.verkocht_id AS `milestone_verkocht_id`,
b.id AS `milestonefase_id`,
b.titel AS `milestonefase_titel`,
b.milestone_id AS `milestonefase_milestone_id`,
b.omschrijving AS `milestonefase_omschrijving`
FROM `milestones` a
INNER JOIN `milestone_parts` b ON a.id=b.milestone_id
WHERE a.verkocht_id = '99'
";
$result= $db->query($dbh, $query);
while ($row = $db->fetchassoc($result))
{
$stone = array($row['milestone_verkocht_id'], $row['milestone_id'], $row['milestone_titel'], $row['client']);
$fase = array($row['milestonefase_milestone_id'],$row['milestonefase_id'],$row['milestonefase_titel']);
$stone[] = $fase;
echo '<pre>'; print_r($stone); echo '</pre>';
}
I get this as result
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 10
[2] => string
)
)
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 11
[2] => string
)
)
but I need (with names) this:
Array
(
[milestone_verkocht_id] => 99 // This is project id
[milestone_id] => 6
[milestone_title] => string
[client] => string
[10] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 10
[milestone_title] => string
)
[11] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 11
[milestone_title] => string
)
[12] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 12
[milestone_title] => string
)
)
Can you help me or do you have a solution? Help me please!
you can cycle each field returned by the query, checking the field name and making new arrays
$stones = array();
while ($row = $db->fetchassoc($result)) {
$fase = array();
$stone = array('milestones' => array());
foreach ($row as $k => $v) {
if (strpos($k, 'milestonefase_') === 0) {
$fase[$k] = $v;
} else {
$stone[$k] = $v;
}
}
if(!isset($stones[$stone['milestone_id']])) {
$stones[$stone['milestone_id']] = $stone;
}
$stones[$stone['milestone_id']]['milestones'][$fase['milestonefase_id']] = $fase;
}
echo '<pre>'.print_r($stones, true).'</pre>';
Edit
made some changes in order to match the request. Now we use $stones to store the information we already have on a milestone, adding to it the different "$fase" returned from the query
Probably a more clean way is to retrieve all the information with two different queries one for milestones and the other for the fases
Edit2
Added a sub-array for the milestone fases

PHP SQL: GROUP BY as array index

I have this query for mysql:
SELECT HOUR(time),COUNT(*) FROM pageview WHERE time >= DATE_SUB(NOW(),INTERVAL 12 HOUR) GROUP BY HOUR(time)
For example, this is the output:
Array
(
[0] => Array
(
[HOUR(time)] => 1
[COUNT(*)] => 1
)
[1] => Array
(
[HOUR(time)] => 10
[COUNT(*)] => 4
)
[2] => Array
(
[HOUR(time)] => 11
[COUNT(*)] => 5
)
)
However I want the output like this
Array
(
[1] => 1
[10] => 4
[11] => 5
)
The array index should be the value of [HOUR(time)].
I would prefer directly by changing the query.
To fetch the data I use this:
$stmt = $db->prepare($query);
$result = $stmt->execute();
$views = $stmt->fetchAll();
indexes in mysql results create automatically , to achieve your goal loop through your first array and create new one as you want
$result = array();
foreach($views as $row) {
$result[$row['HOUR(time)']] = array( 'COUNT(*)' => $row['COUNT(*)']);
}
print_r($result); // check output
or simpler form
$result = array();
foreach($views as $row) {
$result[$row['HOUR(time)']] = $row['COUNT(*)'];
}
print_r($result); // check output
Try with this
$res = array();
foreach($views as $data)
{
$res[$data['HOUR(time)']] = array( 'COUNT(*)' => $data['COUNT(*)']);
}
print_r($res);

PHP $_Session array within array index number

I'm using a session array to store ingredient information. Each added ingredient has it's own array... as such
$_SESSION['ingredients'][] = array($_POST['ingredient'],$_POST['qty']);
Printing the array gives the following..
Array ( [0] => Array ( [0] => 1 [1] => 1 ) [1] => Array ( [0] => 1 [1] => 2 ) [2] => Array ( [0] => 1 [1] => 3 ) )
When pulling out the values of the array I am using the following...
$rows=$_SESSION['ingredients'];
if($rows){
foreach($rows as $row){
$sql = 'SELECT ingredient_name FROM ' . INGREDIENTS_TABLE . ' WHERE ingredient_id = '.$row[0];
$result = $db->sql_query($sql);
$ingredient = $db->sql_fetchrow($result);
$template->assign_block_vars('ingr_list', array(
'INGREDIENT' => $ingredient['ingredient_name'],
'QTY' => $row[1],
'IDENTITY' => ****$id****, <-----HERE
));
}
What I'm looking for is the $id to equal the key value of that particular $row. Do I need to individually search the array each time I want to find it's ID (ie within the loop) or is there an easier solution?
Thanks
I think you need:
foreach($rows as $id => $row){
Looks like you need just
'IDENTITY' => $row[0],

Merge multple arrays from one result into a single array in PHP

I'm really sorry to bug you, put I've got a problem that I've been trying to resolve for quite some time now. I've done some research and have found things like array_merge but it doesn't appear to help me.
Anyway, enough waffle. I have a result of a query that looks something like this:
Array
(
[0] => STRINGA
)
Array
(
[0] => STRINGA
[1] => STRINGB
)
Array
(
[0] => STRINGA
[1] => STRINGB
[2] => STRINGC
)
Array
(
[0] => STRINGD
[1] => STRINGC
[2] => STRINGA
[3] => STRINGB
[4] => STRINGE
[5] => STRINGF
)
How can I combine the above into one array so that the result will look more like:
Array
(
[0] => STRINGA
[1] => STRINGB
[2] => STRINGC
[3] => STRINGD
[4] => STRINGE
[5] => STRINGF
)
Duplicates in the original arrays can be ignored as I only need the string to be placed into the new array once.
Any help would be massively appreciated.
Thank you.
EDITED: This is the block of code that brings out the result from the database:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $splitrow) {
if(NULL != $splitrow) {
$therow = explode(';',$splitrow);
}
//print_r retrieves result shown above
print_r($therow);
}
}
$bigarray = array(
array (
0 => 'STRINGA',
),
array (
0 => 'STRINGA',
1 => 'STRINGB',
),
array(
0 => 'STRINGA',
1 => 'STRINGB',
2 => 'STRINGC',
)
);
$result = array_values(
array_unique(
array_merge( $bigarray[0], $bigarray[1], $bigarray[2] )
)
);
// array_merge will put all arrays together, including duplicates
// array_unique removes duplicates
// array_values will sort out the indexes in ascending order (1, 2, 3 etc...)
$bigarray = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $value){
if($value != NULL){
$therow = explode(';',$value);
foreach($therow as $key=>$values){
//push the value into the single array 'bigarray'
array_push($bigarray, $values);
}
}
}
}
//remove duplicates
$uniquearray = array_unique($bigarray);
//reset key values
$indexedarray = array_values($uniquearray);
print_r($indexedarray);
Thanks to all of those that helped, much appreciated!

Categories