Grouping Array by Value - php

I am looking to group my array into sub arrays when they have the same Supplier ID. I have looked at many similar questions on here but I cannot get any of them to work for me. I have tried foreach loops and even the PHP merge function. I have to use MySQLi for this so I cannot group using PDO.
This is what I have:
Array
(
[supplierID] => 1
[drugID] => 1
[costPrice] => 9.98
[reorderQTY] => 50
)
Array
(
[supplierID] => 1
[drugID] => 2
[costPrice] => 9.98
[reorderQTY] => 50
)
Array
(
[supplierID] => 2
[drugID] => 3
[costPrice] => 9.98
[reorderQTY] => 50
)
This is what I need:
Array
(
[supplierID] => 1
Array
(
[drugID] => 1
[costPrice] => 9.98
[reorderQTY] => 50
)
[drugID] => 2
[costPrice] => 9.98
[reorderQTY] => 50
)
)
Array
(
[supplierID] => 2
Array
(
[drugID] => 3
[costPrice] => 9.98
[reorderQTY] => 50
)
)
This is the PHP where I am outputting the array to get the above result:
if(isset($_POST["automatic"])){
$sql = "SELECT supplierID,drugID,costPrice,reorderQTY FROM drugs WHERE quantityInStock <= reorderLevel";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<pre>";
print_r($row);// I need to sort this array into sub array groups by supplierID key
echo "</pre>";
}
}else{
echo " <tr><td>0 results </td></tr>";
}
mysqli_close($conn);
}

Something like this will do it,
$out = [];
while($row = mysqli_fetch_assoc($result)) {
$out[$row->supplierID][] = $row;
}
Basically I use the supplier id to create an array key, then assign an empty array. Then add all rows with that supplier id to that array.
This will create a multidimensional array.

Related

PHP not showing all data in array from loop

Outputting data to an array
public function GetProfitByMonth($d1, $d2){
$sql=odbc_exec($this->connections, "select con.ID, con.ShortName as NameAK,
ROUND(ISNULL(SUM(tik.TotalSub)-SUM(tik.TotalAG), 0), 2) as Profit,
MONTH(tik.DEALDATE) as month_num
from Counteragent as con
left join Tickets as tik on tik.AgentID=con.ID
where con.ValueType in (2,3) and con.Active='1' and (DEALDATE between '".$d1."' and '".$d2."')
group by con.ID, con.ShortName, MONTH(tik.DEALDATE)
order by con.ShortName, MONTH(tik.DEALDATE) ;");
$tblResult=array();
while ($row = odbc_fetch_array($sql)) {
$tblResult[]=$row;
}
odbc_free_result($sql);
Array
(
[0] => Array
(
[Profit] => 11218.30
[month_num] => 8
)
[1] => Array
(
[Profit] => 1152.15
[month_num] => 8
)
....
[4] => Array
(
[Profit] => 119837.81
[month_num] => 8
)
)
I need to display only month_num => Profi from the array
did this way
$tblResult = array();
while ($row = odbc_fetch_array($sql)) {
$tblResult[$row['mon_num']] = $row['Profit'];
}
odbc_free_result($sql);
return $tblResult;
but as a result in the array shows only the last value:
Array
(
[8] => 119837.81
)
How to make an array show all the data?
This is because month_num = 8 for all entries in your original array.
Your while loops first two iterations effectively evaluate to:
$tblResult[8] = 11218.30
$tblResult[8] = 1152.15
To get the result in the form you want, you need month_num to be unique.

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 mysqli result into an array not working as expected

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?

PHP get value of one column in array

I'm writing some data off my MySQL database into an array using columns with php like this:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row->id = $row["ID"];
$row->product = $row["product"];
$row->aantal = $row["Aantal"];
$row->price = $row["Price"];
$od[] = $row;
}
} else {
echo "0 results";
}
now later I have to use the $row->id and $row->product of the different columns seperatly to get some more data out of another table in MySQL. I've been trying to accomplish this:
$to = 0;
foreach($od as $odt)
{
$odb= $odt[$to]["ID"];
$sql = "SELECT `Name` FROM `detail` WHERE `ID` = '$odb'";
$to++;
But this doesn't seem to work, I've tried dozen of others but can't seem to get this thing right...
Any solutions or remarks?
EDIT:
Array ( [0] => Array ( [ID] => 3 [product] => 10 [Aantal] => 1 [Price] => 3 ) [1] => Array ( [ID] => 4 [product] => 13 [Aantal] => 1 [Price] => 3 ) [2] => Array ( [ID] => 5 [product] => 3 [Aantal] => 3 [Price] => 4 ) )
You are doing it wrong, you are saving object in an array and trying the get the data with array, it should be as
foreach($od as $key=>$odt)
{
$odb= $odt->id;
$sql = "SELECT `Name` FROM `detail` WHERE `ID` = '$odb'";
}

Reading/Accessing 2d/3d array

I did a query on a table that returned two columns of data with 5 rows. I stored these in an array but I can't figure out how to access the data. This is the result of the array:
/*
Array (
[0] => Array (
[contributions] => 99
[key_projects] => 4
)
[1] => Array (
[contributions] => 2
[key_projects] => 26
)
[2] => Array (
[contributions] => 1
[key_projects] => 26
)
[3] => Array (
[contributions] => 0
[key_projects] => 52
)
[4] => Array (
[contributions] => 0
[key_projects] => 53
)
)
*/
$result_array = array();
while ($row = mysqli_fetch_assoc($result)) {
$result_array[] = $row;
}
If I do echo $result_array[0][0] I get Array 0 echo'd.
echo $result_array[0]['contributions']; // displays: 99
echo $result_array[4]['key_projects']; // displays: 53
You are using fetch_assoc withc means your returned arrays will use the keys from your query
so you need to use those to access the data:
echo $result_array[0]['contributions'];
//or
foreach($result_array as $row){
echo "Contributions:".$row['cotributions'].", Key Projects".$row['key_projects']."\n";
}
If you want to use $result_array[0][0] use mysqli_fetch_row instead of mysqli_fetch_assoc
As you are fetching associative array, you have to use names as array indexes.
foreach ($result_array as $v){
echo 'key project: '.$v['key_projects'].'<br>';
echo 'contributions: '.$v['contributions'].'<hr/>';
}

Categories