PHP - Merge two arrays of objects included other objects [duplicate] - php

This question already has answers here:
Merge two arrays containing objects and remove duplicate values
(7 answers)
Closed 5 months ago.
in my symfony project, I need to be able to merge several arrays of objects while removing duplicates.
For example :
array 1 :
Array
(
[0] => Absence Object
(
[id] => 1
[type] => TypeConge Object ([id] => 4, [nom] => "Maladie")
[user] => User Object (......)
[debut] => 12-11-2019 00:00:00
)
[1] => Absence Object
(
[id] => 2
[type] => TypeConge Object ([id] => 5, [nom] => "CA")
[user] => User Object (......)
[debut] => 13-11-2019 00:00:00
)
[2] => Absence Object
(
[id] => 3
[type] => TypeConge Object ([id] => 4, [nom] => "Maladie")
[user] => User Object (......)
[debut] => 11-11-2019 00:00:00
)
)
Array 2:
Array
(
[0] => Absence Object
(
[id] => 1
[type] => TypeConge Object ([id] => 4, [nom] => "Maladie")
[user] => User Object (......)
[debut] => 12-11-2019 00:00:00
)
[1] => Absence Object
(
[id] => 8
[type] => TypeConge Object ([id] => 4, [nom] => "Maladie")
[user] => User Object (......)
[debut] => 17-11-2019 00:00:00
)
)
output:
Array
(
[0] => Absence Object
(
[id] => 1
[type] => TypeConge Object ([id] => 4, [nom] => "Maladie")
[user] => User Object (......)
[debut] => 12-11-2019 00:00:00
)
[1] => Absence Object
(
[id] => 2
[type] => TypeConge Object ([id] => 5, [nom] => "CA")
[user] => User Object (......)
[debut] => 13-11-2019 00:00:00
)
[2] => Absence Object
(
[id] => 3
[type] => TypeConge Object ([id] => 4, [nom] => "Maladie")
[user] => User Object (......)
[debut] => 11-11-2019 00:00:00
)
[3] => Absence Object
(
[id] => 8
[type] => TypeConge Object ([id] => 4, [nom] => "Maladie")
[user] => User Object (......)
[debut] => 17-11-2019 00:00:00
)
)
I use this code to do it :
$demandes = $this->getDemandesValidateur($unUser, $search, $superValidation);
$tabDemandes = array_merge($tabDemandes, $demandes);
$tabDemandes = array_map("unserialize", array_unique(array_map("serialize", $tabDemandes)));
But I get the impression that it causes bugs because of serialization and deserialization. I get the good final table, but some data seems unusable. For example I can not call:
$absence->getType()->getNom();
It returns null sometimes. Is it because of my code ?
My case :
To clarify my case, here's what I'm supposed to do:
I have an empty board at the beginning.
Then I make a loop to retrieve other tables that I merge. And in the end, I remove the duplicates.
It looks like this:
case "ROLE_SUPPLEANT":
$tabDemandes = [];
$users = $this->repoUsers->getUsersWhereIsSuppleant($user);
foreach($users as $unUser)
{
$demandes = array_column($this->getDemandesCongesForCalendar($unUser, $demandesConges, "ROLE_VALIDATEUR"), null, 'id');
$tabDemandes = $tabDemandes + $demandes;
}
if($user->hasRole("ROLE_VALIDATEUR"))
{
$demandes = array_column($this->getDemandesCongesForCalendar($user, $demandesConges, "ROLE_VALIDATEUR"), null, 'id');
$tabDemandes = $tabDemandes + $demandes;
}
break;
Knowing that the function getDemandesCongesForCalendar () returns an array of objects (which themselves contain objects).
I have the impression of having misused the code that you advised me, because it will not remove duplicates I think at the end.
The variable $ requests will in any case contain an array with unique values, there will be no duplicates.
But since each time, I add its values to the general table ($ tabDemands), there may be duplicates in the latter. And that's where I should step in to remove duplicates

Based on splash58's comment, you can use array_column() and then merge arrays while keeping only the first item. A sample can be seen here.
<?php
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
$records2 = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5624,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
$first = array_column($records, null, 'id');
$second = array_column($records2, null, 'id');
$third = $first + $second;
// if you want to reset indexes
// $third = array_values($third);
echo print_r($third);

You can do something like this:
$result = [];
$array1 = [
[
"id" => 1,
"other_data" => "text1"
],
[
"id" => 2,
"other_data" => "text2"
],
[
"id" => 3,
"other_data" => "text3"
],
];
$array2 = [
[
"id" => 1,
"other_data" => "text1"
],
[
"id" => 8,
"other_data" => "text8"
],
];
$merge_array = function($array, $result) {
foreach($array as $element) {
$id = $element["id"]; //In your case it could be $element->getId()
if(!isset($result[$id])) {
$result[$id] = $element;
}
}
return $result;
};
$result = $merge_array($array1, $result);
$result = $merge_array($array2, $result);
print_r(array_values($result));

Related

PHP 7.2 - SQL Server 2017 - Create Nested Array response

I have a Stored Procedure that retrieves data from a SQL Server DB.
With query result I need to populate the parameters' Array of a SOAPClient's Method
At present I'm manually creating the Array, but I was wondering if it was possible (and worthy) to create the Array in the way required by the SOAP Method directly from TSQL:
Using PHP 7.2 - SQL Server 2017
Let me explain with an example:
this is my Query Result:
Array
(
[Key] => R******l
[Password] => c*************z
[AccountNumber] => 0****1
[MeterNumber] => 2******5
[ShipTimestamp] => 2020-10-29T10:24:19+01:00
[ServiceType] => INTERNATIONAL_ECONOMY
[PackagingType] => YOUR_PACKAGING
[PreferredCurrency] => EUR
[Weight_Units] => KG
[TotalWeight] => 0.02
...
)
While it should return something like this:
Array
(
[Authentication] => Array
(
[User] => Array
(
[Key] => R******l
[Password] => c*************z
)
)
[Client] => Array
(
[Account] => 0*******1
[Meter] => 2*******5
)
[Shipment] => Array
(
[ShipTimestamp] => 2020-10-29T10:41:26+01:00
[DropoffType] => REGULAR_PICKUP
[ServiceType] => INTERNATIONAL_ECONOMY
[PackagingType] => YOUR_PACKAGING
[PreferredCurrency] => EUR
[TotalWeight] => Array
(
[Units] => KG
[Value] => 0.02
)
)
...
)
Is it possible and worthy?
You could return one row with one JSON column using FOR JSON PATH1 in SQL and in PHP json_decode($json, true)3 with $assoc param set to true to decode JSON as array.
SELECT (
SELECT user_key [Authentication.User.Key]
, user_password [Authentication.User.Password]
, client_account [Client.Account]
, client_meter [Client.Meter]
--- and so on
FROM my_table
FOR JSON PATH
) [json]
The result should be JSON
{
"Authentication": { "User": { "Key": "XXX", "Password": "XXX" } },
"Client": { "Account": "YYY", "Meter": 200500 }
}
And now You can fetch that value in PHP, decode it and supply to SOAP.
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$json = json_decode($row['json'], true);
But in SQL You need a special syntax to format those types:
date values CONVERT(varchar(10), date_col, 120) -
120 results in 2020-10-29 11:32:00 format, varchar(10) trim just date part, varchar(20) gets whole date+time2
boolean values CAST(boolean_col as bit) (0 -> false, 1 -> true)
More info:
SQL: Format query results as JSON with FOR JSON
SQL: CAST and CONVERT with datetime in different formats
PHP: json_decode
As asked for an example, this can be also done with a mapping.
Data defined as
$data = [
'Key' => 'R******l',
'Password' => 'c*************z',
'AccountNumber' => '0****1',
'MeterNumber' => '2******5',
'ShipTimestamp' => '2020-10-29T10:24:19+01:00',
'ServiceType' => 'INTERNATIONAL_ECONOMY',
'PackagingType' => 'YOUR_PACKAGING',
'PreferredCurrency' => 'EUR',
'Weight_Units' => 'KG',
'TotalWeight' => '0.02',
];
Mapping defined with a hash table. The name may be transformed and groups may me as deep as wanted.
$mapping = [
'Key' => ['name' => 'Key', 'group' => ['Authentication', 'User']],
'Password' => ['name' => 'Password', 'group' => ['Authentication', 'User']],
'AccountNumber' => ['name' => 'Account', 'group' => ['Client']],
'MeterNumber' => ['name' => 'Meter', 'group' => ['Client']],
'ShipTimestamp' => ['name' => 'ShipTimestamp', 'group' => ['Shipment']],
'ServiceType' => ['name' => 'ServiceType', 'group' => ['Shipment']],
'PackagingType' => ['name' => 'PackagingType', 'group' => ['Shipment']],
'PreferredCurrency' => ['name' => 'PreferredCurrency', 'group' => ['Shipment']],
'Weight_Units' => ['name' => 'Units', 'group' => ['Shipment', 'TotalWeight']],
'TotalWeight' => ['name' => 'Value', 'group' => ['Shipment', 'TotalWeight']],
];
Now a simple routine to remap the data by the mapping table and put to $mappedData.
$mappedData = [];
foreach($data as $key => $value) {
$map = $mapping[$key];
$root = array_shift($map['group']);
krsort($map['group']);
$value = [$map['name'] => $value];
foreach($map['group'] as $group) {
$value = [$group => $value];
}
$new[$root] = $value;
$mappedData = array_replace_recursive ($mappedData, $new);
}
Which looks like this when executed
Array
(
[Authentication] => Array
(
[User] => Array
(
[Key] => R******l
[Password] => c*************z
)
)
[Client] => Array
(
[Account] => 0****1
[Meter] => 2******5
)
[Shipment] => Array
(
[ShipTimestamp] => 2020-10-29T10:24:19+01:00
[ServiceType] => INTERNATIONAL_ECONOMY
[PackagingType] => YOUR_PACKAGING
[PreferredCurrency] => EUR
[TotalWeight] => Array
(
[Units] => KG
[Value] => 0.02
)
)
)

Remove duplicate combination of elements from multidimensional array

I have an array with fields:
$products = array(
[0] => array('name' => 'product_one', 'category' => 'category_one', employee => '3234'),
[1] => array('name' => 'product_two', 'category' => 'category_two', employee => '5421'),
[2] => array('name' => 'product_three', 'category' => 'category_one', employee => '3234'),
[3] => array('name' => 'product_one', 'category' => 'category_one', employee => '2153'),
[4] => array('name' => 'product_one', 'category' => 'category_two', employee => '6312')
)
Now, in this case, employee field is not important, but the combination of product/category is unique.
Wanted result:
$products = array(
[0] => array('name' => 'product_one', 'category' => 'category_one', employee => '3234'),
[1] => array('name' => 'product_two', 'category' => 'category_two', employee => '5421'),
[2] => array('name' => 'product_three', 'category' => 'category_one', employee => '3234'),
[4] => array('name' => 'product_one', 'category' => 'category_two', employee => '6312')
)
Any idea what is the best way to do this? On production, I have more than 30.000 elements and usually around 10 duplicates. Also in real database, I have 12 fields and a combination of 4 of them needs to be unique).
If you don't mind which of the duplicates you keep, it's probably simplest to iterate over the loop, making a new array with keys which are a combination of the required unique values (I've used a separator of ## in this code, you can use anything that cannot occur in the values). This way duplicates will be automatically removed as an array cannot have identical keys. Once the loop is done the output array can be re-indexed numerically using array_values:
$output = array();
foreach ($products as $p) {
$output["{$p['name']}##{$p['category']}"] = $p;
}
$output = array_values($output);
print_r($output);
Output (for your sample data):
Array
(
[0] => Array
(
[name] => product_one
[category] => category_one
[employee] => 2153
)
[1] => Array
(
[name] => product_two
[category] => category_two
[employee] => 5421
)
[2] => Array
(
[name] => product_three
[category] => category_one
[employee] => 3234
)
[3] => Array
(
[name] => product_one
[category] => category_two
[employee] => 6312
)
)
Demo on 3v4l.org

Php check and replace if value exist in multi array?

Problem:
I dont know/understand how to check if date and place exists on the same "row" and they exists more then once.
Second, how do i then merge an array
my case MergeArray with ArraySchedule
Code:
$ArraySchedule = array();
while ($data = $stmt -> fetch(PDO::FETCH_ASSOC)) {
$schedules = array(
"id" => $data['id'],
"name" => $data['name'],
"date" => $data['date'],
"time" => $data['time'],
"place_id" => $data['place_id'],
"place" => $data['place'],
);
array_push($ArraySchedule, $schedules);
}
$dupe_array = array();
foreach ($ArraySchedule as $key => $value) {
if(++$dupe_array[$value["date"]] > 1 && ++$dupe_array[$value["place_id"]] > 1 ){
// this statement is wrong, i want something like:
// if date and place_id exists on the same "row" and they exists more then once
}
}
What i want to do:
Check if ArraySchedule contains schedules that have the same date and place,
if there is more than one schedule that has the same date and place_id.
then I want to update ArraySchedule with this structure
$MergeArray = array(
"id" => ArraySchedule['id'],
"name" => array(
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
),
"date" => $ArraySchedule['date'],
"time" => $ArraySchedule['time'],
"place_id" => $ArraySchedule['place_id'],
"place_name" => $ArraySchedule['place_name'],
),
MergeArray with ArraySchedule?
anyway...
Output I think I want?
Print_r($ArraySchedule)
array(
[0] =>
array(
[id] => 1
[names] => Simon
[date] => 2019-01-02
[time] 18.00
[place_id] => Tystberga Park
[place] => Tystberga
)
[1] =>
array(
[id] => 2
//[names] insted of [name]?
[names] =>
array(
[name] => Vincent
[name] => Angel
[name] => Kim
)
[date] => 2019-02-17
[time] => 13.00
[place_id] => Borås Park
[place] => Borås
)
[2] =>
array(
[id] => 3
// [names] is always an array?
[names] => Caitlyn
[date] => 2019-03-15
[time] 13.00
[place_id] => Plaza Park
[place] => EvPark
)
)
You can use array-reduce. Consider the following:
function mergeByDateAndPlace($carry, $item) {
$key = $item["place_id"] . $item["date"]; // creating key matching exact place and date
if (!isset($carry[$key])) {
$carry[$key]["name"] = $item["name"];
} else {
$carry[$key] = $item;
$item["name"] = [$item["name"]]; // make default array with 1 element so later can be append other names
}
return $carry;
}
Now use it with:
$MergeArray = array_reduce($ArraySchedule, "mergeByDateAndPlace", []);
If you later want to know if there were any duplicate you can just loop on $MergeArray. You can also use array_values if you want to discard the concat keys.
Notice #Nick 2 important comment about saving the first loop and the "time" value that need to be decided. Also notice your desire output contain multi element with the same key ("name") - you need to append them with int key - Array can not have duplicate keys.
Hope that helps!
Here is my data from my database:
var_export($ArraySchedule)
array (
0 => array ( 'id' => '225', 'place_id' => 'Alviks Kulturhus', 'name' => 'BarraBazz', 'date' => '2019-03-19', 'placeadress' => 'Gustavslundsvägen 1', ),
1 => array ( 'id' => '229', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Anders Björk', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
2 => array ( 'id' => '230', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Black Jack', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
3 => array ( 'id' => '227', 'place_id' => 'Arosdansen Syrianska Kulturcentret', 'name' => 'BarraBazz', 'date' => '2019-05-08', 'placeadress' => 'Narvavägen 90', ),
4 => array ( 'id' => '228', 'place_id' => 'Aspåsnäset', 'name' => 'Blender', 'date' => '2019-05-25', 'placeadress' => 'Aspåsnäset 167', ),
5 => array ( 'id' => '226', 'place_id' => 'Arenan Västervik Resort', 'name' => 'Blender', 'date' => '2019-06-29', 'placeadress' => 'Lysingsvägen', ),
6 => array ( 'id' => '222', 'place_id' => 'Alingsåsparken', 'name' => 'Bendéns', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
7 => array ( 'id' => '223', 'place_id' => 'Alingsåsparken', 'name' => 'Charlies', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
8 => array ( 'id' => '224', 'place_id' => 'Allhuset Södertälje', 'name' => 'Cedrix', 'date' => '2019-07-16', 'placeadress' => 'Barrtorpsvägen 1A', ), )
I want to update the "name" with an array of names everytime that place_id and date are the same.
This is the output I want:
Array (
[0] =>
Array ( [id] => 225 [place_id] => Alviks Kulturhus [name] => BarraBazz [date] => 2019-03-19 [placeadress] => Gustavslundsvägen 1 )
[1] =>
Array ( [id] => 229 [place_id] => Axelhuset Göteborg [name] => Array([0] => Anders Björk [1] => Black Jack ) [date] => 2019-04-08 [placeadress] => Axel Dahlströms torg 3 )
[3] =>
Array ( [id] => 227 [place_id] => Arosdansen Syrianska Kulturcentret [name] => BarraBazz [date] => 2019-05-08 [placeadress] => Narvavägen 90 )
[4] =>
Array ( [id] => 228 [place_id] => Aspåsnäset [name] => Blender [date] => 2019-05-25 [placeadress] => Aspåsnäset 167 )
[5] =>
Array ( [id] => 226 [place_id] => Arenan Västervik Resort [name] => Blender [date] => 2019-06-29 [placeadress] => Lysingsvägen )
[6] =>
Array ( [id] => 222 [place_id] => [Alingsåsparken] [name] => Array([0] => Bendéns [1] => Charlies) [date] => 2019-07-16 [placeadress] => Folkparksgatan 3A )
[8] =>
Array ( [id] => 224 [place_id] => Allhuset Södertälje [name] => Cedrix [date] => 2019-07-16 [placeadress] => Barrtorpsvägen 1A ) )
Here is my updated code
$sql = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` ORDER BY `date`";
$stmt = $db -> prepare($sql);
$stmt -> execute();
$ArraySchedule = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_export($ArraySchedule);
$DatePlace = array();
foreach ($ArraySchedule as $key => $Schedule){
$Arrayquery = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` WHERE `schedule`.`date`= :date_ AND `schedule`.`place_id` = :place_id ORDER BY `date`";
$ArrayStmt = $db->prepare($Arrayquery);
$ArrayStmt -> execute(array(":date_" => $Schedule['date'],":place_id" => $Schedule['place_id']));
//Getting every $Schedule that has the same date and place_id
if($ArrayStmt->rowCount() > 1){
//Here i want two update the name inside
//$ArrayArraySchedule with an array of names
//that has the same place and date?
}
}
print_r($ArraySchedule);

Multidimensional indexed array to associative array depending on column value

I have a multidimensional indexed array. Each element is an associative array with an id column which is unique between elements (its value never repeats within the array).
[indexed] =>Array
(
[0] => Array
(
[id] => john
[name] => John
[age] => 29
),
[1] => Array
(
[id] => peter
[name] => Peter
[age] => 30
),
[2] => Array
(
[id] => harry
[name] => Harry
[age] => 19
)
)
My goal is to convert this array into a multidimensional associative array, indexed by id values.
[indexed] =>Array
(
[john] => Array
(
[id] => john
[name] => John
[age] => 29
),
[peter] => Array
(
[id] => peter
[name] => Peter
[age] => 30
),
[harry] => Array
(
[id] => harry
[name] => Harry
[age] => 19
)
)
My best attempt so far is to loop over array elements and manually create the final array.
$associative = array();
foreach($indexed as $key=>$val) $associative[$val['id']] = $val;
I think it's not the most elegant solution. Is it possible to obtain the same result with built-in (more efficient) functions?
The truth is php DOES offer a single, native function that allows you to replace the outer indexes with the values of a single column. The "magic" is in the 2nd parameter which tells php not to touch the subarray values when assigning the new keys.
Code: (Demo)
$indexed = [
['id' => 'john', 'name' => 'John', 'age' => 29],
['id' => 'peter', 'name' => 'Peter', 'age' => 30],
['id' => 'harry', 'name' => 'Harry', 'age' => 19],
];
var_export(array_column($indexed, null, 'id'));
Output:
array (
'john' =>
array (
'id' => 'john',
'name' => 'John',
'age' => 29,
),
'peter' =>
array (
'id' => 'peter',
'name' => 'Peter',
'age' => 30,
),
'harry' =>
array (
'id' => 'harry',
'name' => 'Harry',
'age' => 19,
),
)
This even works on an array of objects. The end result is an array of objects with new, associative first-level keys. (Demo)
$indexed = [
(object)['id' => 'john', 'name' => 'John', 'age' => 29],
(object)['id' => 'peter', 'name' => 'Peter', 'age' => 30],
(object)['id' => 'harry', 'name' => 'Harry', 'age' => 19],
];
var_export(array_column($indexed, null, 'id'));
Output:
array (
'john' =>
(object) array(
'id' => 'john',
'name' => 'John',
'age' => 29,
),
'peter' =>
(object) array(
'id' => 'peter',
'name' => 'Peter',
'age' => 30,
),
'harry' =>
(object) array(
'id' => 'harry',
'name' => 'Harry',
'age' => 19,
),
)
Here is another way of doing it (assuming $arr is your original array):
$associative = array_combine(array_map(function($item) { return $item['id']; }, $arr), $arr);
But I think using a foreach is still shorter and more readable compare to this.

Compact multidimensional Array

i've a similar array:
Array
(
[0] => Array
(
[id] => 1
[name] => Mario
[type] => Doctor
[operations] => brain
[balance] => 3.00
)
[1] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => hearth
[balance] => 6.00
)
[2] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => hands
[balance] => 4.00
)
[3] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => foots
[balance] => 1.00
)
)
I must to merge it for id, so obtain only 2 elements for array (0 and 1) and Luca (id 3) must be unified for operations, in a new array, similar to this, so in future print more clearly operations unified and not divided.
[...]
)
[1] => Array
(
[id] => 3
[name] => luca
[type] => doctore
[operations] => Array (6.00 hearts,
4.00 hands,
1.00 foots)
)
I can not figure how solve my trouble... Someone could help me please? Thank you very much to all!
<?php
$input = array(
array('id' => 1, 'name' => 'Mario', 'type' => 'Doctor', 'operations' => 'brain', 'balance' => 3.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'hearth', 'balance' => 6.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'hands', 'balance' => 4.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'foots', 'balance' => 1.00),
);
$output = array();
foreach ($input as $person)
{
// Add the person to the output, if needed.
if (array_key_exists($person['id'], $output) === false)
{
$output[$person['id']] =
array(
'id' => $person['id'],
'name' => $person['name'],
'type' => $person['type'],
'operations' => array(),
);
}
// Add the operation to the array of operations.
$output[$person['id']]['operations'][] =
array(
'type' => $person['operations'],
'balance' => $person['balance'],
));
}
foreach ($output as $person)
{
if (count($person['operations']) === 1)
{
// If the array contains only 1 item, pull it out of the array.
$output[$person['id']]['operations'] = $person['operations'][0];
}
}
print_r($output);

Categories