How to combine 2 arrays into single one? - php

I have 2 arrays, as you will see bellow, and I want theme to combine into a single one. First 2 arrays have sub-arrays with a sum and a month. The result array(3rd), must have the sum of first 2 arrays for the same month.
array:3 [
0 => array:2 [
"sum" => 179.0
"month" => "2016-01"
]
1 => array:2 [
"sum" => 34.0
"month" => "2016-02"
]
2 => array:2 [
"sum" => 67.0
"month" => "2016-03"
]
]
array:2 [
0 => array:2 [
"sum" => 143.25
"month" => "2016-01"
]
1 => array:2 [
"sum" => 479.0
"month" => "2016-03"
]
]
Total:
array:3 [
0 => array:3 [
"sum" => 313.25
"month" => "2016-01"
]
1 => array:2 [
"sum" => 34.0
"month" => "2016-02"
]
2 => array:2 [
"sum" => 546.0
"month" => "2016-03"
]
]
What I tried:
for($i=0;$i<count($com1);$i++){
for ($j=0; $j < count($com2); $j++) {
if($com1[$i]['month'] == $com2[$j]['month']){
$total = $com1[$i]['sum']+$com2[$j]['sum']
}
}
}
But it doesn't give the result I want
I am abit noob...I hope someone can help. Thanks

Try this:
$com1 = [
0 => [
'sum' => 179.0,
'month' => '2016-01'
],
1 => [
'sum' => 34.0,
'month' => '2016-02'
],
2 => [
'sum' => 67.0,
'month' => '2016-03'
]
];
$com2 = [
0 => [
'sum' => 143.25,
'month' => '2016-01'
],
1 => [
'sum' => 479.0,
'month' => '2016-03'
]
];
$total = [];
foreach ($com1 as $data) {
$total[$data['month']] = $data;
}
foreach ($com2 as $data) {
if (!isset($total[$data['month']])) {
$total[$data['month']] = [
'sum' => 0,
'month' => $data['month']
];
}
$total[$data['month']]['sum'] += $data['sum'];
}
print_r($total);

Here is a solution that generates a non-associative array (as you indicated in your question):
$month_idx = []; // helper to identify at which index a certain month is stored
$result = [];
foreach (array_merge($data1, $data2) as $idx => $row) {
$month = $row["month"];
if (!isset($month_idx[$month])) {
$month_idx[$month] = count($result);
$result[] = $row;
} else {
$result[$month_idx[$month]]["sum"] += $row["sum"];
}
}
var_export($result);
When $data1 and $data2 are:
$data1 = array (
array(
"sum" => 179.0,
"month" => "2016-01"
),
array(
"sum" => 34.0,
"month" => "2016-02"
),
array(
"sum" => 67.0,
"month" => "2016-03"
)
);
$data2 = array (
array(
"sum" => 143.25,
"month" => "2016-01"
),
array(
"sum" => 479.0,
"month" => "2016-03"
)
);
Then output is:
array (
0 =>
array (
'sum' => 322.25,
'month' => '2016-01',
),
1 =>
array (
'sum' => 34,
'month' => '2016-02',
),
2 =>
array (
'sum' => 546,
'month' => '2016-03',
),
)

Related

Laravel Array or Object?

i'm kinda new with Laravel Framework. And now confused with data type like array and object. I got a data like this :
"data[0].detailItem" => array:2 [
0 => array:3 [
"itemNo" => "100011"
"unitPrice" => 0
"quantity" => 6
]
1 => array:3 [
"itemNo" => "102972"
"unitPrice" => 0
"quantity" => 3
]
]
is there a way I change it into :
"data[0].detailItem" => [
{
"itemNo" => "100011"
"unitPrice" => 0
"quantity" => 6
},
{
"itemNo" => "102972"
"unitPrice" => 0
"quantity" => 3
}
]
Edit :
Heres the code
public function apiStore(Request $request){
$detailReceiveItem = DB::table('t_receive_item_detail')->where('receive_item_id','=',$request->idReceiveItem)->get();
$detailItem = [];
foreach($detailReceiveItem as $key=>$receiveItem){
$temp = [
'itemNo' => $receiveItem->item_code,
'unitPrice' => 0,
'quantity' => $receiveItem->qty,
];
array_push($detailItem,$temp);
}
$input = [
'data[0].vendorNo' => $request->vendorNo,
'data[0].receiveNumber' => $request->receiveNumber,
'data[0].transDate' => date('d/m/Y',strtotime($request->transDate)),
'data[0].detailItem' => (object)$detailItem
];
$insertReceiveItem = Http::withHeaders([
'Authorization' => 'Bearer '.session()->get('access_token'),
'X-Session-ID' => session()->get('X-Session-ID'),
])->asForm()->post(session()->get('host').'api url here',$input);
return response()->json(['status'=>1, 'url'=>'/api-accurate/receive-item','message'=>'Receive Item Created Successfully!']);
}
That's my code. I need to convert $detailItem into a object.

PHP - Sort array by subarray value based on a second array

I've done some research including going through PHP Sort Array By SubArray Value but this is a variation:
I have an array as follows:
$data =
[
0 => [
'id' => (int) 5,
'name' => 'Foo',
'group_id' => (int) 1,
],
1 => [
'id' => (int) 6,
'name' => 'Bar',
'group_id' => (int) 1,
],
2 => [
'id' => (int) 8,
'name' => 'Baz',
'group_id' => (int) 7,
],
3 => [
'id' => (int) 9,
'name' => 'ABC',
'group_id' => (int) 2,
],
4 => [
'id' => (int) 10,
'name' => 'DEF',
'group_id' => (int) 65,
]
];
I also have an array second array of group_id's that are relevant to a search a user has performed:
$gids = [7, 65];
What I want to do is order $data by group_id based on the values inside $gids. So the order of $data should become:
0 => [
'id' => (int) 8,
'name' => 'Baz',
'group_id' => (int) 7,
],
1 => [
'id' => (int) 10,
'name' => 'DEF',
'group_id' => (int) 65,
]
2 => [
'id' => (int) 5,
'name' => 'Foo',
'group_id' => (int) 1,
],
3 => [
'id' => (int) 6,
'name' => 'Bar',
'group_id' => (int) 1,
],
4 => [
'id' => (int) 9,
'name' => 'ABC',
'group_id' => (int) 2,
],
Note that once the $gids array has been taken into account, the group_id of the remaining items in $data is numerical (ascending order in this case: 1, 1, 2).
I understand it's possible to use usort and an anonymous function, e.g.
usort($data, function ($gids) {
});
However, I don't understand what to write inside this function to perform ordering in this way? My initial thought was to do a foreach($gids) followed by a foreach($data) and compare the group_id value. But I don't know what to do in terms of modifying $data so that it reorders.
Please can someone help?
Equally, if there is already a post which explains how to do this please let me know, because I couldn't find one on here. The original link simply bases ordering numerically, not on a second array ($gids equivalent).
Using PHP 7.1.0
This should do the trick
usort($data, function($a, $b) use ($gids)
{
$posA = array_search($a['group_id'], $gids);
if ($posA === false) {
$posA = 9999;
}
$posB = array_search($b['group_id'], $gids);
if ($posB === false) {
$posB = 9999;
}
return $posA - $posB;
});
If found in the array of $gids, the sorting of $gids will be used, else the elements will stay in the order they're given in.
The return I'm getting is the following:
array:5 [▼ 0 => array:3 [▼
"id" => 8
"name" => "Baz"
"group_id" => 7 ] 1 => array:3 [▼
"id" => 10
"name" => "DEF"
"group_id" => 65 ] 2 => array:3 [▼
"id" => 5
"name" => "Foo"
"group_id" => 1 ] 3 => array:3 [▼
"id" => 6
"name" => "Bar"
"group_id" => 1 ] 4 => array:3 [▼
"id" => 9
"name" => "ABC"
"group_id" => 2 ] ]

Php array transformation and combination

So I have array like this one
[
'custid' => [
'customer_number_1' => '20098374',
'customer_number_8' => '20098037',
'customer_number_15' => '20098297'
],
'destid' => [
'destination_numbers_1' => [
(int) 0 => '20024838',
(int) 1 => '20041339'
],
'destination_numbers_8' => [
(int) 0 => '20008293'
],
'destination_numbers_15' => [
(int) 0 => '20016969',
(int) 1 => '20022919',
(int) 2 => '20025815',
(int) 3 => '20026005',
(int) 4 => '20027083',
(int) 5 => '20045497'
]
]
]
Goal is to merge cust id with destid in pairs and should look like so
[
(int) 0 => [
'user_id' => (int) 1,
'sap_customer_id' => '20098374',
'sap_destination_id' => '20024838'
],
(int) 1 => [
'user_id' => (int) 1,
'sap_customer_id' => '20098374',
'sap_destination_id' => '20041339',
],
(int) 2 => [
'user_id' => (int) 1,
'sap_customer_id' => '20098037',
'sap_destination_id' => '20008293,
],
(int) 3 => [
'user_id' => (int) 1,
'sap_customer_id' => '20098297'
'sap_destination_id' => '20016969',
],
...
I have tried with code below, but I am getting destination_id number as array and duplicated customer numbers. Also I have tried with array walk but result is same.
$data = [];
foreach ($sap_data['custid'] as $custid) {
foreach ($sap_data['destid'] as $destid) {
$data[] = [
'user_id' => 1,
'sap_customer_id' => $custid,
'sap_destination_id' => $destid
];
}
}
Thx for helping!
You should make inner loop in other way
foreach($sap_data['custid'] as $k => $custid) {
// Make destination key
$dkey = str_replace('customer_number', 'destination_numbers', $k);
// And get array, for example, destination_numbers_1 for customer_number_1
foreach ($sap_data['destid'][$dkey] as $destid) {
$data[] = [
'user_id' => 1,
'sap_customer_id' => $custid,
'sap_destination_id' => $destid
];
}
}
demo on eval.in

Finding the lowest value for specific key in a deeply nested array

Given an array with the following structure:
$orders = [
0 => [
'volume' => 1926,
'lowPrice' => 1000.00,
'date' => 2016-12-29 00:45:23
],
1 => [
'volume' => 145,
'lowPrice' => 1009.99,
'date' => 2016-12-31 14:23:51
],
2 => [
'volume' => 19,
'lowPrice' => 985.99,
'date' => 2016-12-21 09:37:13
],
3 => [
'volume' => 2984,
'lowPrice' => 749.99,
'date' => 2017-01-01 19:37:22
],
// ...
]
I'm looking for the most performant way to find the lowest value for lowPrice. The size of $orders will more than likely be larger than 500 items. For the given array, the result would be as follows:
$lowestPrice = $this->findLowestPrice($orders);
echo $lowestPrice; // 749.99
Extract an array of lowPrice and find the min():
echo min(array_column($orders, 'lowPrice'));
Since those appear to be floats, you'll probably want number_format() or money_format().
If you're only interested in the value of the lowest price (not the index in the array or something) you can use array_reduce:
$orders = [
0 => [
'volume' => 1926,
'lowPrice' => 1000.00,
'date' => "2016-12-29 00:45:23"
],
1 => [
'volume' => 145,
'lowPrice' => 1009.99,
'date' => "2016-12-31 14:23:51"
],
2 => [
'volume' => 19,
'lowPrice' => 985.99,
'date' => "2016-12-21 09:37:13"
],
3 => [
'volume' => 2984,
'lowPrice' => 749.99,
'date' => "2017-01-01 19:37:22"
],
];
$lowestPrice = array_reduce(
$orders,
function($c, $v)
{
if ($c === null)
return $v["lowPrice"];
return $v["lowPrice"] < $c ? $v["lowPrice"] : $c;
}
);

Recursive count of children in nested arrays + changing values by reference

I know this is basic recursion but I get stuck anyway :(
I need to count how many elements each element has below it (children, grandchildren,...) and write that value into original array.
My example array:
$table = [
1 => [
'id' => 1,
'children_count' => 0
],
2 => [
'id' => 2,
'children_count' => 0,
'children' => [
3 => [
'id' => 3,
'children_count' => 0,
'children' => [
4 => [
'id' => 4,
'children_count' => 0,
'children' => [
5 => [
'id' => 5,
'children_count' => 0
],
6 => [
'id' => 6,
'children_count' => 0
]
]
]
]
]
]
]
];
My recursion code:
function count_children(&$array){
foreach($array['children'] as &$child){
if(isset($child['children'])){
$array['children_count'] += count_children($child);
}
else return 1;
}
}
Call for recursion:
//call for each root element
foreach($table as &$element){
if(isset($element['children'])) count_children($element);
}
Expected output:
$table = [
1 => [
'id' => 1,
'children_count' => 0
],
2 => [
'id' => 2,
'children_count' => 4,
'children' => [
3 => [
'id' => 3,
'children_count' => 3,
'children' => [
4 => [
'id' => 4,
'children_count' => 2,
'children' => [
5 => [
'id' => 5,
'children_count' => 0
],
6 => [
'id' => 6,
'children_count' => 0
]
]
]
]
]
]
]
];
Where did I got it wrong?
My function does something, element 3 gets value 1, but thats about it.
Here is the ideone link: http://ideone.com/LOnl3G
function count_children(&$table){
$count1 = 0;
foreach($table as &$array) {
$count = 0;
if (isset($array['children'])) {
$count += count($array['children']);
$count += count_children($array['children']);
}
$array['children_count'] = $count;
$count1 += $count;
}
return $count1;
}
count_children($table);
print_r($table);

Categories