I need to add new elemets to my array when a new category value is encountered. When a category value is encountered after the first time, its value1 and value2 values should be added to the first encounter's respective values.
Also, in the result array, I no longer wish to keep the category column. The category-grouping rows should use the category value as its name value.
Sample input:
$datas = [
[
'category' => 'Solution',
'name' => 'Name1',
'value1' => 20,
'value2' => 21
],
[
'category' => 'Solution',
'name' => 'Name2',
'value1' => 30,
'value2' => 31
],
[
'category' => 'Solution1',
'name' => 'Name3',
'value1' => 40,
'value2' => 41
]
];
Desired result:
[
['name' => 'Solution', 'value1' => 50, 'value2' => 52],
['name' => 'Name1', 'value1' => 20, 'value2' => 21],
['name' => 'Name2', 'value1' => 30, 'value2' => 31],
['name' => 'Solution1', 'value1' => 40, 'value2' => 41],
['name' => 'Name3', 'value1' => 40, 'value2' => 41]
]
I tried like this:
private function groupByProductSuperCategory($datas)
{
$return = [];
foreach ($datas as $data) {
$return[$data['category']][$data['name']] = array_sum(array_column('category', $data);
}
return $return;
}
The idea is to calculate first all sum values for by category, and after that just put values from name like another array. Have you an idea of how to do that?
From the posted array... To end in the desired array, there is some tiny fixes to do first. But I assumed it was due to typos while copying here...
So here is the array I started with:
$result = [
0 => [
"category" => 'Solution',
"name" => 'Name1',
"value1" => 20,
"value2" => 21
],
1 => [
"category" => 'Solution',
"name" => 'Name2',
"value1" => 30,
"value2" => 31
],
2 => [
"category" => 'Solution1',
"name" => 'Name3',
"value1" => 40,
"value2" => 41
]
];
Now, that re-organization of the data is a bit more complex than it looks... You need to perform several loops to:
Find distinct "category" names
Perform the summations for each
Add the sum item and the single items
So here is the code I ended with:
function groupByProductSuperCategory($datas){
$category = [];
$return = [];
// Find distinct categories
foreach ($datas as $data) {
if(!in_array($data["category"],$category)){
array_push($category,$data["category"]);
}
}
// For each distinct category, add the sum item and the single items
foreach ($category as $cat) {
// Get the sums
if(!in_array($cat,$return)){
$sum1 = 0;
$sum2 = 0;
foreach ($datas as $data) {
if($data["category"] == $cat){
$sum1 += $data["value1"];
$sum2 += $data["value2"];
}
}
}
// Push the sums in the return array
array_push($return,[
"name" => $cat,
"value1" => $sum1,
"value2" => $sum2,
]);
// Push the single elements
foreach ($datas as $data) {
if($cat == $data["category"]){
array_push($return,[
"name" => $data["name"],
"value1" => $data["value1"],
"value2" => $data["value2"],
]);
}
}
}
return $return;
}
Here is a PHPFiddle to try it out... Hit [F9] to run.
It is much more direct, efficient, and readable to implement a single loop and push reference variables into the result array to allow summing based on shared categories without keeping track of the actual indexes of the category rows.
Code: (Demo)
$result = [];
foreach ($array as $row) {
if (!isset($ref[$row['category']])) {
$ref[$row['category']] = [
'name' => $row['category'],
'value1' => 0,
'value2' => 0
];
$result[] = &$ref[$row['category']];
}
$ref[$row['category']]['value1'] += $row['value1'];
$ref[$row['category']]['value2'] += $row['value2'];
unset($row['category']);
$result[] = $row;
}
var_export($result);
Related
I have a a number of values/IDs that need to be translated to a single ID, what is the recommended method using PHP?
For example, I want IDs 38332, 84371, 37939, 1275 to all translate to ID 1234 and IDs222, 47391, 798 to all translate to ID 1235, etc. .
I'm thinking PHP has something built-in to handle this efficiently?
I'm thinking PHP has something built-in to handle this efficiently?
You can use the standard array as a map, quickly translating one ID to another:
$table[38332]; # int(1234)
depending on how you store your overall translation table, you can create a function that returns the translation from its input:
$table = $translation('I want IDs 38332, 84371, 37939, 1275 to all translate to ID 1234');
$result = $table[1275] ?? null; # int(1234)
Example:
$parseId = static fn(string $i) => (int)trim($i);
$translation = static fn(string $buffer): array
=> preg_match_all('~((?:\d+,\s*)+\d+)\s+to all translate to ID\s*(\d+)~', $buffer, $_, PREG_SET_ORDER)
? array_reduce($_, static fn (array $carry, array $item): array => [
$ids = array_map($parseId, explode(',', $item[1])),
$carry += array_fill_keys($ids, $parseId($item[2])),
$carry,][2], []) : [];
This is pretty easy to accomplish with PHP, here's one way you could do it:
Using this method, you populate the $map array, using the id you want to replace with as the key, and the value being an array of the keys you want to be replaced. It then calculates a simple key => value array based on this to make comparison a lot quicker.
Instead of creating a copy of the data, you could use foreach ($data as &$record)
$data = [
[
'id' => 1,
'foreign_id' => 38332,
'text' => 'a'
],
[
'id' => 2,
'foreign_id' => 84371,
'text' => 'b'
],
[
'id' => 3,
'foreign_id' => 37939,
'text' => 'c'
],
[
'id' => 4,
'foreign_id' => 1275,
'text' => 'd'
],
[
'id' => 5,
'foreign_id' => 222,
'text' => 'e'
],
[
'id' => 5,
'foreign_id' => 47391,
'text' => 'f'
],
[
'id' => 5,
'foreign_id' => 798,
'text' => 'g'
]
];
$map = [
123 => [
38332,
84371,
37939,
1275
],
1235 => [
222,
47391,
798
]
];
// Calculate a map to speed things up later
$map_calc = [];
foreach ($map as $destination_id => $ids) {
foreach ($ids as $id) {
$map_calc[$id] = $destination_id;
}
}
$new_data = [];
foreach ($data as $record) {
if (isset($map_calc[$record['foreign_id']]))
$record['foreign_id'] = $map_calc[$record['foreign_id']];
$new_data[] = $record;
}
var_dump($new_data);
[
0 => [
'qty' => 10
'section' => 'VK7B'
'time_window' => 1
]
1 => [
'qty' => 1
'section' => 'STIC'
'time_window' => 1
]
2 => [
'qty' => 1
'section' => 'STIC'
'time_window' => 1
]
]
I have this multidimensional array where I want to merge the array's if both the section and the time_window are the same, summing the qty for that array. What is an elegant way to do this?
I have tried this ($sections being the multidimensional arry), but this changes the keys and only checks for one value:
$new = []
foreach ($sections as $s) {
if (isset($new[$s['section']])) {
$new[$s['section']]['qty'] += $s['qty'];
$new[$s['section']]['time_window'] = $s['time_window'];
} else {
$new[$s['section']] = $s;
}
}
[
'VK7B' => [
'qty' => 10
'section' => 'VK7B'
'time_window' => 1
]
'STIC' => [
'qty' => 2
'section' => 'STIC'
'time_window' => 1
]
]
As pointed by #RiggsFolly in the comment you are not checking time_window are the same.
You can do it with this code:
$new = []
foreach ($sections as $s) {
// you need to save both values (section and time_window) to check both of them
if (isset($new[$s['section'].$s['time_window']])) {
$new[$s['section'].$s['time_window']]['qty'] += $s['qty'];
$new[$s['section'].$s['time_window']]['time_window'] = $s['time_window'];
} else {
$new[$s['section'].$s['time_window']] = $s;
}
}
// Now $new is an associative array => let's transform it in a normal array
$new = array_values($new);
I'm trying to loop through this array to output side by side for every iteration.
$cars = [
'BMW' => [
'Year' => '2020',
'Body' => 'Sedan',
'Mileage' => '100'
],
'Ford' => [
'Year' => '2019',
'Body' => 'SUV',
'Mileage' => '500'
]
];
$count = count(reset($cars));
for($i=0; $i<$count; $i++) {
foreach($cars as $key => $value) {
echo $cars[$key][$i]. '<br>';
}
}
My expected result for every iteration.
2020,2019
Sedan,SUV
100,500
I have searched through some links, but none is specific to a multidimensional array.
Two arrays in foreach loop
How can I loop through two arrays at once?
The other question you point to is about having separate arrays of data, which you could sort of emulate by splitting the main array into parts.
This solution assumes that all of the keys for the values you want are in the first item (as in your example, they all have the 3 values) and loops over the first array element and uses array_column() to extract all of the values from all of the main array elements for that key. Then implode() these values to put them as a CSV list...
foreach ( $cars[array_keys($cars)[0]] as $key => $value) {
echo implode(",", array_column($cars, $key)).PHP_EOL;
}
which with your test data gives...
2020,2019
Sedan,SUV
100,500
You can simply do it by storing your desired array values in another array and then implode them or make them work by your need. Take a look at the following code..
$cars = [
'BMW' => [
'Year' => '2020',
'Body' => 'Sedan',
'Mileage' => '100'
],
'Ford' => [
'Year' => '2019',
'Body' => 'SUV',
'Mileage' => '500'
],
];
$year = [];
$body = [];
$milage = [];
foreach( $cars as $key => $car ){
if( $car['Year'] ){
$year[] = $car['Year'];
}
if( $car['Body'] ){
$body[] = $car['Body'];
}
if( $car['Mileage'] ){
$milage[] = $car['Mileage'];
}
}
var_dump(implode( ',', $year));
var_dump(implode( ',', $body));
var_dump(implode( ',', $milage));
will give you output:
string(9) "2020,2019" string(9) "Sedan,SUV" string(7) "100,500"
I want to combine two arrays of objects. Let me give you an example:
Example:
// First array:
$array1 = [
{ name => 'Joe', p_id => 1 },
{ name => 'Bob', p_id => 2 },
{ name => 'Sam', p_id => 4 }
]
// Second array:
$array2 = [
{ id => 1, name => 'X' },
{ id => 2, name => 'Y' },
{ id => 4, name => 'Z' }
]
Expected output:
$output = [
{ name => 'Joe + X', id => 1 },
{ name => 'Bob + Y', id => 2 },
{ name => 'Sam + Z', id => 4 }
]
Goal:
I want the fastest possible way to combine the name property in the second array with the name property in the first array.
Note: The p_id property in the first array is the same as the id property in the second array.
What i try:
I've used nested loops that have a very low speed.
array_map is the solution!
Given:
$first = [
{ name => 'Joe', p_id => 1 },
{ name => 'Bob', p_id => 2 },
{ name => 'Sam', p_id => 4 },
];
$second = [
{ id => 1, name => 'X' },
{ id => 2, name => 'Y' },
{ id => 4, name => 'Z' },
];
The solution is just simply:
$result = array_map(
static function (\stdClass $first, \stdClass $second): array {
return [
'name' => $first->name . ' + ' . $second->name,
'id' => $first->p_id,
];
},
$first, $second
);
PS: I assume the objects are \stdClass, replace it by the correct one.
Here is a solution for when the ids of the elements inside the array are not in order. Notice that I have changed the order of $array1. Just a bit better than the regular nested loops, on the loop of the $array2 it will remove the "found" elements to improve speed of the next loop.
From:
// First array:
$array1 = [
(object) ['name' => 'Joe', 'p_id' => 1],
(object) ['name' => 'Sam', 'p_id' => 4],
(object) ['name' => 'Bob', 'p_id' => 2],
];
// Second array:
$array2 = [
(object) ['id' => 1, 'name' => 'X'],
(object) ['id' => 2, 'name' => 'Y'],
(object) ['id' => 4, 'name' => 'Z'],
];
Solution:
$result = [];
foreach ($array1 as $array1Element) {
for ($i=0;$i<count($array2);$i++) {
if ($array1Element->p_id === $array2[$i]->id) {
$array2[$i]->name = $array1Element->name . ' + ' . $array2[$i]->name;
$result[] = $array2[$i];
unset($array2[$i]);
$array2 = array_values($array2);
break;
}
}
}
I want to know that is there a way to insert certain elements of an array into a new array. I mean I have an array containing 10 objects. Each object has 3 or four fields for example id, name , age , username. now I want to insert the id's of all the objects into the new array with a single call.Is there anyway to do that.
$array = [
[0] => [
id =>
name =>
],
[1] = > [
id =>
name =>
]
]
and so on now I want to insert all the id's of all the object into a new array with a single call. Is there a way to do that?
Use array_map() function.
Here is your solution:-
$ids = array_map( function( $arr ){
return $arr["id"];
}, $arr );
echo '<pre>'; print_r($ids);
A basic foreach loop will do the job just fine
$firstArray = array(
array(
'id' => 1,
'name' => 'abc'
),
array(
'id' => 2,
'name' => 'def'
),
array(
'id' => 3,
'name' => 'gh'
)
);
$onlyIds = array();
$onlyKeys = array();
//To get the array value 'id'
foreach($firstArray as $value){
$onlyIds[] = $value['id'];
}
//To get the array keys
foreach($firstArray as $key => $value){
$onlyKeys[] = $key;
}
You could use array_walk which could be considered a "single call"
$array = array(0 => array('id', 'name', 'age'), 1 => array('id', 'name', 'age'));
array_walk($array, function($item, $key) {
// $key is 0 or 1
// $item is either id, name, age
});
You can use array_column.
$arr = [ ['id' => 1, 'username' => 'a'], ['id' => 2, 'username' => 'b'] ];
$ids = array_column($arr, 'id')
$ids == [1, 2]