Merge array in for loop using PHP - php

I have following query in loop for select records
$shopchairs=$rows['shop_chairs']; //coming dynamically i.e. 1 or 3 or 4
$result = [];
for($i=1;$i<=$shopchairs;$i++)
{
$query = //SELECT QUERY WITH WHERE CONDITION;
$res = $query->result_array();
$result[] = [
'chairnumber' => $i,
'status' => $querys->num_rows() > 0 ? 'booked' : 'available',
'estimateTime' => "",
];
}
echo "<pre>";print_R($result);
Now I just want to merge "estimateTime" which is coming from $res(array) with $result(array), How can I do this?
Right now my $res showing following array in the loop
Array
(
[0] => Array
(
[shopId] => 2
[duration] => 20
[estimatedTime] => 11.3000
)
)
Array
(
)
Array
(
)
Array
(
)
I just want to merge estimatedTime with $result array

Related

Grouping Array by Value

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.

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 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 Multidimensional Associative Array - how to get list of keys?

Here is an example of my data:
[204] => Array
(
[1] => Array
(
[leads] => 9
)
[2] => Array
(
[leads] => 15
)
)
[200] => Array
(
[1] => Array
(
[leads] => 7
)
[2] => Array
(
[leads] => 16
)
[3] => Array
(
[leads] => 5
)
)
I am at the stage where I trying to output the array data into a table but how do I set up the table headers dynamically so that the columns will be 1 | 2 | 3, even if some subsets don't have an array of that type?
The array is constructed from the results of a database query like so:
$dailytotals[$store][$campaigntypeid] = array('leads'=> $leads);
I tried a for each but just realised that it wouldn't work since not all subsets have all columns.
Is there a way to get what I am trying to find?
Try this
$columns = array();
foreach ($your_array as $key=> $arr) {
$columns = array_unique(array_merge($columns, array_keys($arr)));
}
Another way
$columns = array_reduce($your_array,
function ($r, $val) {
return array_unique(array_merge($r, array_keys($val)));
},
array()
);

Combining two arrays PHP

I'm busy with sorting the structure of a menu in my application. Once the menu is reorderd by the user, the values (say; Menu item 1, Menu item 2, etc) are still in the same place.
Now I have two arrays, one that holds the way they are sorted (Array 1) and one that holds the values of the menu items. (Array 2)
Example of both arrays;
(Array 1, that holds the keys)
Array
(
[0] => 1
[1] => 2
[2] => 0
)
The above array's values are the keys for the new array.
(Array 2, holds the values)
Array
(
[0] => value_0
[1] => value_1
[2] => value_2
)
So I thought it would be best to create a new array which consist out of;
The values of Array 1
The values of Array 2
However, i'm running into a problem. I want the values in array 2 to stick to their keys. So lets say I change the position of value_0 to the last, the new array would look like this;
Array
(
[1] => value_1
[2] => value_2
[0] => value_0
)
Is there a way to achieve this or am I doing it completely wrong?
Edit
Ok, so multidemensional array it is. However i'm having problems creating one.
Array 1 and Array 2 both come from the database. Array 1 with the sorting order and Array 2 contains the values. Now, the values in array 2 are stored like this; value1,value2,value3. So to be able to work with them I explode on , (comma).
The results on the fetchs are both different;
For the first array it returns as many as how many values there are.
(So if there are 3 values, it will return 3 different positions.)
For the second array it will return 18 records, since this is tied to
other menu items (sub menu's etc).
So for the first array I do;
while ($row = mysql_fetch_assoc($result_query_test)) {
$positions[] = $row['position'];
}
For the second array I do;
while ($row = mysql_fetch_assoc($result_values)) {
$array_values = explode(',', $row['values']);
}
From then on i'm having problems creating the multidimensinonal array;
while ($row = mysql_fetch_assoc($result_values)) {
$array_values = explode(',', $row['values']);
foreach ($positions as $new_key) {
foreach ($array_values as $value) {
$new_array[] = array('key' => $new_key, 'value' => $value);
}
}
}
Edit two:
This is what I use now;
(Since $all_values is a multidimensional array because I have to explode on the values beforehand.)
foreach ($all_values as $values) {
foreach ($values as $key => $value) {
$new_array[] = array('key' => $positions[$key], 'value' => $value);
}
}
This is what the $new_array returns;
Array
(
[0] => Array
(
[key] => 0
[value] => value_0
)
[1] => Array
(
[key] => 2
[value] => value_2
)
[2] => Array
(
[key] => 1
[value] => value_1
)
[3] => Array
(
[key] => 0
[value] => value_0
)
[4] => Array
(
[key] => 2
[value] => value_2
)
[5] => Array
(
[key] => 1
[value] => value_1
)
Now I need to get the values and implode them with comma's. However, since not every 3 values (value_0, value_1, value_3) are together I can't do that now.
In this example there are 3 keys, (0,1,2) which should be a different array along with their values, like you did in your example:
Array (
[0] = Array (
[key] = 1,
[value] = value_1
),
[1] = Array (
[key] = 2,
[value] = value_2
),
[2] = Array (
[key] = 0,
[value] = value_0
)
)
Why not make a multidimensional array?
$arrayThree =
Array (
[0] = Array (
[key] = 1,
[value] = value_1
),
[1] = Array (
[key] = 2,
[value] = value_2
),
[2] = Array (
[key] = 0,
[value] = value_0
)
)
No matter what order they're in, the key and value are always the set.
foreach ($arrayThree as $tempArray)
{
echo $tempArray['key'];
echo $tempArray['value'];
}
Create Array
$arrayOne = array();
$arrayTwo = array();
$arrayThree = array();
$query = 'SELECT key FROM table1 ';
$result = mysql_query($query) or die(mysql_error());
while($data = mysql_fetch_assoc($result))
{
$arrayOne[] = $data['key'];
}
$query = 'SELECT value FROM table2 ';
$result = mysql_query($query) or die(mysql_error());
while($data = mysql_fetch_assoc($result))
{
$arrayTwo[] = $data['value'];
}
foreach($arrayOne as $key => $value)
{
$arrayThree[] = array('key' => $value, 'value' => $arrayTwo[$key]);
}
You can always use the mysqli or PDO versions, if you're using them.
Example Data
//THESE MIMIC YOUR SELECT RESULTS
$test_keys = array(1,2,3);
$test_values = array('value_1', 'value_2', 'value_3');
//DEFAULTS
$arrayOne = array();
$arrayTwo = array();
$arrayThree = array();
//WHILE FIRST SELECT
for($i=0;$i<count($test_keys);$i++)
{
$arrayOne[] = $test_keys[$i];
}
//WHILE SECOND SELECT
for($i=0;$i<count($test_values);$i++)
{
$arrayTwo[] = $test_values[$i];
}
//MAKE THE FINAL ARRAY
foreach($arrayOne as $key => $value)
{
$arrayThree[] = array('key' => $value, 'value' => $arrayTwo[$key]);
}
//CHECK THE OUTPUT FOR THE NEW ARRAY
echo '<pre>'.print_r($arrayThree,true).'</pre>';
Example Output
Array
(
[0] => Array
(
[key] => 1
[value] => value_1
)
[1] => Array
(
[key] => 2
[value] => value_2
)
[2] => Array
(
[key] => 3
[value] => value_3
)
)
Imploded List
$implodeValues = array_map(function($item) { return $item['value']; }, $arrayThree);
$implodeVariable = implode(',', $implodeValues);
echo $implodeVariable;
Implode Output
value_1,value_2,value_3
I think you can obtain what you want doing this:
$new = array();
for($i = 0, $len = count($array1), $i < $len, ++$i) {
$new[$array1[$i]] = $array2[$i];
}
now $new contains the values in the order you want them

Categories