May 17, 2022
16
Level 3
How to efficiently map between an existing array to query Collection result?
I have an array containing several objects with keys initialized to 0 except for the first key in each object which is initialized to certain date:
$data = [];
for ($i=0; $i<4; $i++) {
$data[] = (object)['main_key' => DateTime formatted string, 'key1' => '0', 'key2' => '0'];
}
I also have a query that groups by main_key and returns a result:
Illuminate\Support\Collection {
#items: array:4 [
0 => {
+"main_key": 2022-05
+"key1": "some_value"
+"key2": "some_value"
}
1 => {
+"date": 2022-05
+"key1": "some_value"
+"key2": "some_value"
}
2 => {
+"date": 2022-04
+"key1": "some_value"
+"key2": "some_value"
}
3 => {
+"date": 2022-03
+"key1": "some_value"
+"key2": "some_value"
}
]
How can I map the values so that the values of key1 and key2 will be set in the correct date? (they have the same number of objects)
Level 54
@cooperino can you supply a sample of what you would like the array to look like?
if i get what you mean, you want:
array(3) {
["2022-05"]=>
array(3) {
["date"]=>
string(7) "2022-05"
["public"]=>
int(10)
["private"]=>
int(20)
}
["2022-04"]=>
array(3) {
["date"]=>
string(7) "2022-04"
["public"]=>
int(0)
["private"]=>
int(5)
}
["2022-03"]=>
array(3) {
["date"]=>
string(7) "2022-03"
["public"]=>
int(11)
["private"]=>
int(33)
}
}
which you can get doing the following:
$data = [
0 => [
"date" => '2022-05',
"private" => 20,
],
1 => [
"date" => '2022-05',
"public" => "10",
],
2 => [
"date" => '2022-04',
"private" => 5,
],
3 => [
"date" => '2022-03',
"public" => 11,
],
4 => [
"date" => '2022-03',
"private" => 33,
],
];
$results = [];
foreach ($data as $row){
$results[$row['date']] = [
'date' => $row['date'],
'public' => (int) ($row['public'] ?? $results[$row['date']]['public'] ?? 0),
'private' => (int) ($row['private'] ?? $results[$row['date']]['private'] ?? 0),
];
}
var_dump($results);
1 like
Please or to participate in this conversation.