Summarize the same key name in php multidimensional array - php

I have an array like this:
[0] => Array
(
[id_station] => 2397
[hour] => 12
[data] => Array
(
[cameraon] => 355654
[cameraoff] => 4532
[camerabroken] => 76745
...
)
)
[1] => Array
(
[id_station] => 2399
[hour] => 13
[data] => Array
(
[cameraon] => 3905466
[cameraoff] => 1672
[camerabroken] => 70780
...
)
)
I want to add one more row = total of all items
[1] => Array
(
[id_station] =>
[hour] =>
[data] => Array
(
[cameraon] => 4261120
[cameraoff] => 6204
[camerabroken] => 147525
)
)
I used array_sum(array_column($array["data], 'cameraon')) but I have to do for all items cameraon, cameraoff, camerabroken (I have a hundred items).
Is there any way to get total row in this case?

I assume that you don't know the depth of data sub-array. (that is how many key-value pairs are there)
So do like below:-
$final_array = [];
$final_array['id_station'] ='';
$final_array['hour'] ='';
foreach($original_array as $original_arr){
foreach($original_arr['data'] as $key=>$original){
$final_array['data'][$key] +=$original;
}
}
Output:-https://eval.in/926729

You wish to sum the columnar data, so leveraging array_sum() and array_column() are wise choices. The only thing left to do is set up the loop.
You can first isolate the data subarrays using array_column() then "drill down" into the first subarray to iterate each column. Use the column names to access all values in all columns. This makes the method dynamically successful regardless of the complexity of your data subarrays.
Code: (Demo)
$array=[
[
'id_station'=>2397,
'hour'=>12,
'data'=>['cameraon'=>355654,'cameraoff'=>4532,'camerabroken'=>76745]
],
[
'id_station'=>2399,
'hour'=>14,
'data'=>['cameraon'=>3905466,'cameraoff'=>1672,'camerabroken'=>70780]
]
];
$datas=array_column($array,'data'); // isolate the data subarrays
foreach(current($datas) as $column=>$data){ // iterate the columns
$result[$column]=array_sum(array_column($datas,$column)); // sum the column values
}
$array[]=['id_station'=>'','hour'=>'','data'=>$result]; // completenew item and append
var_export($array); // print to screen
Output:
array (
0 =>
array (
'id_station' => 2397,
'hour' => 12,
'data' =>
array (
'cameraon' => 355654,
'cameraoff' => 4532,
'camerabroken' => 76745,
),
),
1 =>
array (
'id_station' => 2399,
'hour' => 14,
'data' =>
array (
'cameraon' => 3905466,
'cameraoff' => 1672,
'camerabroken' => 70780,
),
),
2 =>
array (
'id_station' => '',
'hour' => '',
'data' =>
array (
'cameraon' => 4261120,
'cameraoff' => 6204,
'camerabroken' => 147525,
),
),
)

Related

split one array have two key split into two array in php

Question :
I have one array have two key or more split into two or more create array based on array in php.
my Array :
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I want output like this :
output:
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
)
)
array(
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I am not sure how you want to store those arrays, but let me help you.
I assume you have a datastructure like this, so one array with multiple values.
array (
key1 => ...values...,
key2 => ...values...,
...
key_n => ...values...
)
And you want something like this, si multiple arrays with single keys well you need to store that array somehow.
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
If you do not know the exact number of arrays, you can't $array1, $array2, ... $array_n and it also not efficent, so you shoudl have an array of arrays. So something like this:
array(
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
)
So you should iterate trough the keys of the input array and then
So the code
<?php
//example input array
$arr = array (
"key1" => "val1",
"key2" => "val2"
);
$keys = array_keys($arr); //get the keys of the input array, see phpdoc
$output = [];
foreach($keys as $key) {
$output[] = array ($arr[$key]);
}
?>
This will output an array of arrays, with single key of the inner array.
If this is not you answer, reply.
Research:
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/control-structures.foreach.php
php.net - arrays manual Example #6 Accessing array elements
Maybe this document will help you
This may also help you
<?php
$stdArray = array(
"foo" => "bar",
42 => 24,
"dimensional" => array(
"fname" => "jon",
"lname" => "doe",
),
"multi" => array(
"RAJAHMUNDRY" => array(
"unspcp_code" => 46182005,
"head_quarter" => "RAJAHMUNDRY",
0 => 2
),
"HYDERABAD" => array(
"unspcp_code" => 46182005,
"head_quarter" => "HYDERABAD",
0 => 2
),
)
);
print_r($stdArray);
print_r($stdArray["multi"]);
print_r($stdArray["multi"]["RAJAHMUNDRY"]);

Combine multiple array with one array key

I have a situation in PHP where I need to combine multiple array values and bind with the first array key, Let say I have following array,
[services] => Array
(
[0] => 1
[1] => 2
[2] => 1
)
[package_type] => Array
(
[0] => 1
[1] => 2
[2] => 1
)
[service_desc] => Array
(
[0] => Full HD
[1] => Full HD
[2] => Full HD
)
[service_price] => Array
(
[0] => 500
[1] => 600
[2] => 500
)
Now , I want to bind all array with service type keys like services[0] will have the value of package_type[0], service_desc[0] and service_price[0]. The purpose is that I can easily identify all service related values with its Id. Can anyone suggest ?
array_map is key here. Leave the first argument as null and it will group as you want:
<?php
$data =
[
'services' =>
[
'programming',
'debugging'
],
'description' =>
[
'the process of writing computer programs.',
'the process of identifying and removing errors from software/hardware'
]
];
$result = array_map(null, $data['services'], $data['description']);
var_export($result);
Output:
array (
0 =>
array (
0 => 'programming',
1 => 'the process of writing computer programs.',
),
1 =>
array (
0 => 'debugging',
1 => 'the process of identifying and removing errors from software/hardware',
),
)
Instead of writing out all your keys as arguments you could unpack like this:
array_map(null, ...array_values($data));
For something more elaborate, pass array_map a callable:
$keys = array_keys($data);
$result = array_map(function(...$args) use ($keys) {
return array_combine($keys, $args);
}, ...array_values($data));
var_export($result);
Output:
array (
0 =>
array (
'services' => 'programming',
'description' => 'the process of writing computer programs.',
),
1 =>
array (
'services' => 'debugging',
'description' => 'the process of identifying and removing errors from software/hardware',
),
)

PHP reorder multidimensional array based on single dimensional array

multidimensional array
Array
(
[0] => Array
(
[ID] => 5068
[Item] => 2737
[Unit] => 15
)
[1] => Array
(
[ID] => 5067
[Item] => 2737
[Unit] => 13
)
)
single dimensional array
Array (
[0] => 11
[1] => 13
[2] => 15
)
Expected output:
Array
(
[0] => Array
(
[ID] => 5067
[Item] => 2737
[Unit] => 13
)
[1] => Array
(
[ID] => 5068
[Item] => 2737
[Unit] => 15
)
)
It not necessary that single dimensional array must be in ASC/DESC order. I want to reorder multidimensional array according to single dimensional array based on unit value. How can I achieve this?
Maybe something like this would work?
$multiDimArray = [
0 => [
'ID' => 5068,
'Item' => 2737,
'Unit' => 15
],
1 => [
'ID' => 5067,
'Item' => 2737,
'Unit' => 13
]
];
$singleDim = [
11,13,15
];
usort($multiDimArray,function($a,$b){
global $singleDim;
return ($singleDim[0] >= $a['Unit']) ? -1 :1;
});
print_r($multiDimArray);
there's something in back of my head that tells me I'm missing something. But feel free to give it a go.
Assuming that the values in the single array all map to a value in Unit, you could loop the single dimensional array and then loop the values in the multidimensional array.
In the inner loop use in_array to check if the value from the single dimensional array occurs in the multidimensional array. If it does, you could for example add it to a new array.
$result = [];
foreach ($singleDimension as $sm) {
foreach ($multiDimensional as $md) {
if (in_array($sm, $md)) {
$result[] = $md;
}
}
}
Demo

PHP merge arrays with same key to one custom array

I have multiple result from mysql in array like this
Array1
Array
(
[type] => Food
[storage] => S5213
[quantity1] => 1000
[in1] => 10/09/2017
[quantity2] => 1000
[in2] => 10/09/2017
)
Array 2
Array
(
[type] => Food
[storage] => S4512
[quantity1] => 990
[in1] => 13/09/2017
)
Array 3
Array
(
[type] => Drink
[storage] => K4221
[quantity1] => 12000
[in1] => 12/09/2017
)
So, i would like to merge if the key such as "type" from different arrays are same and put it into custom array. At the same time, it maybe has quantity1, quantity2, quantity3 and in1,in2,in3 for different stocks quantity and date. Would like to merge it into "rack".
Expected result
Array
(
[Food] => Array
(
[0] => Array
(
[storage] => S5213
[rack] => Array
(
[0] => Array
(
[quantity] => 1000
[in] => 10/09/2017
)
[1] => Array
(
[quantity] => 1000
[in] => 10/09/2017
)
)
)
[1] => Array
(
[storage] => S4512
[rack] => Array
(
[0] => Array
(
[quantity] => 990
[in] => 13/09/2017
)
)
)
)
[Drink] => Array
(
[0] => Array
(
[storage] => K4221
[rack] => Array
(
[0] => Array
(
[quantity] => 12000
[in] => 12/09/2017
)
)
)
)
)
Is it possible? tried using array_merge_recursive, but not output expected result.
If this is what your SQL query returns, then it looks like your database is not normalised. More concretely, you should not have columns quantity1, quantity2, ...etc in a single table. The rule is, if you have more than one of some field, create a separate table. In this case that table should just have a foreign key, maybe a sequence number (1, 2, ...) and finally a single quantity column. Multiple quantities would be expressed as multiple rows in that additional table. The in field could be added to that, as it seems to follow the same rule.
Anyway, for the given situation, you could use this PHP function:
function addArray(&$main, $arr) {
if (!is_array($main)) $main = []; // first time
$main[$arr["type"]][] = [
"storage" => $arr["storage"],
"rack" => array_reduce(array_keys($arr), function ($acc, $key) use ($arr) {
if (strpos($key, "quantity") === 0) {
$acc[] = [
"quantity" => $arr[$key],
"in" => $arr[str_replace("quantity", "in", $key)]
];
}
return $acc;
}, [])
];
}
Use it as follows:
$arr = [
"type" => "Food",
"storage" => "S5213",
"quantity1" => 1000,
"in1" => "10/09/2017",
"quantity2" => 1000,
"in2" => "10/09/2017"
];
addArray($main, $arr);
$arr = [
"type" => "Food",
"storage" => "S4512",
"quantity1" => 990,
"in1" => "13/09/2017"
];
addArray($main, $arr);
$arr = [
"type" => "Drink",
"storage" => "K4221",
"quantity1" => 12000,
"in1" => "12/09/2017"
];
addArray($main, $arr);
... etc. $main will have the desired structure.

smaller array based on array contents

I am looking for a way to create a new array based on array contents.
so i've got:
Array ( [0] => 1
[type] => first_value_i_need
[some_id] => 2
[hits] => 88
[some_other_id] => second_value_i_need
)
and i would like to get
Array ( [0] => 1
[app_name] => "first_value_i_need-second_value_i_need"
[hits] => "88"
)
I know that i need some sort of foreach function, but i'm right now lost.
No, you don't need any loops as long as you know which keys you need.
$old = array(
0 => 1,
'type' => 'first_value_i_need',
'some_id' => 2,
'hits' => 88,
'some_other_id' => 'second_value_i_need'
);
$new = array(
0 => $old[0],
'app_name' => $old['type'].'-'.$old['some_other_id'],
'hits' => $old['hits'],
);
So basically do you wnat to get rid of the app_table_id key ?
You can do unset($array['app_table_id']);
And if you need to change some value you can do :
$array['app_name'] = $array['some_other_id'];
//> Note i posted this before your edit.

Categories