This question already has answers here:
Merge the rows of two arrays (appending row data from one array to a row in another array)
(4 answers)
Closed 2 months ago.
I have two arrays:
$array1 =
[
0 =>
[
'data1' => value1
],
1 =>
[
'data1' => value2
]
];
$array2 =
[
0 =>
[
'data2' => value1
],
1 =>
[
'data2' => value2
]
];
Only i want create this:
$arrayFinish =
[
0 =>
[
'data1' => value1,
'data2' => value1
],
1 =>
[
'data1' => value2
'data2' => value2
]
];
I have done this:
foreach ($data1 as $key=>$val)
{
$arrayFinish[] =
[
$val,
];
foreach ($data2[$key] as $key2=>$val2)
{
array_push($arrayFinish[$key],['data2'=>$val2]);
}
}
My actually result:
array:2 [▼
0 => array:2 [▼
0 => {#1546 ▼
+"data1": "BWQHCLJCH"
}
1 => {#1547 ▼
+"data2": "00308F000825"
}
]
1 => array:2 [▼
0 => {#1548 ▼
+"data1": "OTGSAVJIU"
}
1 => {#1549 ▼
+"data2": "00308F000946"
}
]
]
I am trying to do it using PHP. I am blocked right now, i am sure that that the solution is using two loops, but i am doing any bad. If you can see my actually result is not similar to my wish result.
thank u for the help.
Thank u to all that tried to help me. I find a solution.
I am tried to clear the array
foreach ($array1 as $key=>$val)
{
$arrayFinish[$key] = $val;
foreach ($array2[$key] as $key2=>$val2)
{
array_push($arrayFinish[$key],["data2"=>$val2]);
}
}
Using a for cycle i can have access using one iteration to the information. This is not the great solution that i tried to find but working.
Best regards
if your both arrays would have same no of indexes then you can do using below code
foreach ($array1 as $key=>$val) {
$arrayFinish [] = [ $array1[$key], $array2[$key] ];
}
Related
I'm pulling my hair on a proble which seems very simple, but I can't find a solution.
I have a simple $row array here :
array:2 [▼
"reference" => "ABCDEF"
"quantity" => "10"
]
I'm trying to parse it and retrieve quantities per reference using :
$line = [
'ref' => strtoupper($row["reference"]),
'quantity' => $row["quantity"]
];
I'm looping through array of lines using this code:
foreach ($rows as $row) {
$line = [
'ref' => strtoupper($row['reference']),
'quantity' => $row['quantity']
];
}
As a test, my main array $rows has 2 lines :
^ array:3 [▼
0 => array:2 [▼
0 => "ABCDEF"
1 => "10"
]
1 => array:2 [▼
0 => "WXCVBN"
1 => "3"
]
2 => array:1 [▼
0 => null
]
]
However, I'm getting the following error :
Undefined index: reference
Strangely enough, if I comment out the
'ref' => strtoupper($row["reference"]),
line, I can get the "quantity" value with no issue...
I know the key is in there, since the debug of the $row object gives the above result.
It must be dead simple... but I can't find the solution...
If anyone could please help ?
So apparently the $row variable a row from a bigger array that is used in a foreach loop.
This might be the solution to your problem.
$array = [
[ "reference" => "ABC", "quantity" => "10"],
[ "reference" => "ABC", "quantity" => "10"],
[ "reference" => "ABC", "quantity" => "10"],
];
$line[] = '';
foreach($array as $row)
{
$line['ref'] = $row['reference'];
$line['quantity'] = $row['quantity'];
}
In this example $array is your bigger array, i use it to test the example.
After that i create a empty array $line to append the "new" data.
Could you try this?
Edit:
After taking a look at your loop and the array i noticed that your array doesnt have a reference key. Can you try strtoupper(row[0])?
Viewing your code seems that you convert $row array to $line without rewrite key in new array.
your code
foreach ($rows as $row) {
$line = [
'ref' => strtoupper($row['reference']),
'quantity' => $row['quantity']
];
}
With your rewrite you can access $line data by index, not by key
array:3 [▼
0 => array:2 [▼
0 => "ABCDEF"
1 => "10"
]
...
]
My solution
If you want to access your $line data by key, you need to rewrite your loop as:
foreach($rows as $rowData) {
foreach($rowData as $rowKey => $rowValue) {
$data = [
'ref' => $rowKey => strtoupper$($rowValue),
'quantity' => $row['quantity']
];
}
$line[] = $data;
}
Basically, I am building html form inputs that have dynamic inputs For example In below example if user want to increase the unit_type then user can add the new input from front end and send it to store
Note: If user will add the unit_type then all others keys will automatically added. Like if user try to increase the unit_type then unit_address and all other inputs increase accordingly.
Right Now I have the array like this
array:7 [
"unit_type" => array:2 [
0 => null
1 => null
]
"unit_address" => array:2 [
0 => null
1 => null
]
"unit_phone" => array:2 [
0 => null
1 => null
]
"fax" => array:2 [
0 => null
1 => null
]
"installed_capacity" => array:2 [
0 => null
1 => null
]
"production_capacity" => array:2 [
0 => null
1 => null
]
"unit_email" => array:2 [
0 => null
1 => null
]
]
Expected Result
[
[
//Here all keys contain the first values of all arrays
'unit_type'=>'first_value',
'unit_address'=>'first_value',
'unit_phone'=>'first_value',
'fax'=>'first_value',
'installed_capacity'=>'first_value',
'production_capacity'=>'first_value',
'unit_email'=>'first_value'
],
[
//Here all keys contain the second values of all arrays
'unit_type'=>'second_value',
'unit_address'=>'second_value',
'unit_phone'=>'second_value',
'fax'=>'second_value',
'installed_capacity'=>'second_value',
'production_capacity'=>'second_value',
'unit_email'=>'second_value'
]
]
Loop through the existing return data and build the new array like so:
$input_array = []; //your data received from the front end
$return_array = []; //structured data return
foreach($input_array as $field => $fieldData){
foreach ($fieldData as $key => $data){
$return_array[$key][$field] = $data;
}
}
I have a array list, How can I get with PHP the highest key value pair in an array?
array:4 [
0 => array:2 [
"free_shipping" => true
"coupon_amt" => 20
]
1 => array:2 [
"coupon_amt" => 120
"free_shipping" => false
]
2 => array:2 [
"free_shipping" => false
"coupon_amt" => 100
]
3 => array:2 [
"coupon_amt" => 200
"free_shipping" => true
]
]
Any ideas or suggestions on how I can or should do this?
array:4 [
0 => array:2 [
"free_shipping" => true
"coupon_amt" => 200
]
]
A simple loop seems the best option to me.
$max = null;
foreach ($array as $part) {
if ($max === null || $part['coupon_amt'] > $max['coupon_amt']) {
$max = $part;
}
}
Could you try this:
First Convert the array to collection
$collection = collect($array);
And then sort it
$sorted = $collection->sortByDesc('coupon_amt');
then if you want it to be array again just do this
$array = $sorted->toArray();
then just get the first array
$first = $array[0];
Hope it helps!
Use the collections' available methods such as max and where.
<?php
$collection = collect($array);
print_r($collection->where('coupon_amt',$collection->max('coupon_amt'))->all());
$collection = collect($array);
print_r($collection->where('coupon_amt',$collection->max('coupon_amt'))->all());
This question already has answers here:
How to count array with group by
(2 answers)
Closed 4 months ago.
I have 2 log files which i read and get the contents as array.
The array which i get is like this:
2 => array:9 [▼
"app" => "a.log"
"context" => "local"
"level" => "error"
"level_class" => "danger"
"level_img" => "exclamation-triangle"
"date" => "2018-10-25 21:01:04"
"text" => "Class 'Arcanedev\Support\Collection' not found
]
3 => array:9 [▼
"app" => "b.log"
"context" => "local"
"level" => "error"
"level_class" => "danger"
"level_img" => "exclamation-triangle"
"date" => "2018-10-26 16:49:07"
I need to get the count of all the error levels for each file.
For example:
a.log => "count of error level for a.log",
b.log => "count of error levels for b.log"
I have tried:
foreach($names as $filename){
$logs = $this->getLogs($this->filepath.$filename);
$result = array();
$result[ $filename ] = $logs;
foreach($logs as $log){
//$result[ $log['level'] ][] = $log;
$result[ $filename ][] = $log;
$counts = array_map('count', $result);
}
}
which gives me this result:
array:1 [▼
"a.log" => 20
]
Any help is appreciated.
Thank you in advance. :)
i solved the issue myself. I was tried another approach and it seemed to work.
Here is the solution:
foreach($names as $filename){
$logs = $this->getLogs($this->filepath.$filename);
$result = array();
foreach($logs as $log){
$result[ $log['app'] ][] = $log;
$counts = array_map('count', $result);
}
}
and the result:
array:2 [▼
"b-laravel.log" => 3
"laravel.log" => 7
]
Thank You.
Something like
print_r(array_count_values(array_column($array, 'app')));
I would test it but you didn't provide an array i can use. In theory it should work.
My goal is to be able to update a key value inside of an array inside of an array and I'm don't know if I'm using the right php array function.
BEFORE:
array:2 [
"week_number" => 1
"games" => array:1 [
0 => array:3 [
"game_number" => 1
"umpires" => []
"teams" => []
]
]
]
AFTER:
array:2 [
"week_number" => 1
"games" => array:1 [
0 => array:3 [
"game_number" => 1
"umpires" => []
"teams" => [1,2]
]
]
]
Test Class:
private function validParams($overrides = [])
{
return array_merge_recursive([
'week_number' => 1,
'games' => [[
'game_number' => 1,
'umpires' => [],
'teams' => [],
]]
], $overrides);
}
$response = $this->actingAs($this->authorizedUser)
->post(route('games.store', ['week' => $this->week->id]), $this->validParams([
'games' => [][
[
'teams' => [1,2]
]
]
]));
If you want to update the keys... typing $array['new_key'] = $array['old_key'] will duplicate the value with 2 sets of keys.
You have a few options here. Either you create a new array and just set your desired keys or work with array_keys and array_values and mix them up... your choice
http://php.net/manual/en/ref.array.php
See the list above, there are a lot of array functions you can use... see the two above and array_map... there is virtually a great number of ways you can do this. See how your problem is best handled after reviewing the documentation.
Good luck!
This is the moment where you need unset(): Adding a value with a different key will not update or overwrite the old value but simply add another key-value pair.
Hence, add the new value fist, then unset the old one. We can use To array_walk to itterate over the array:
array_walk($array, function (& $item) {
$item['new_key'] = $item['old_key'];
unset($item['old_key']);
});
Take note of the & reference operator in the lambda function: it ensures we are working on the original array and not a copy of it.
I found this as a solution.
private function validParams($overrides = [])
{
return array_replace_recursive([
'week_number' => 1,
'games' => [
0 => [
'game_number' => 1,
'umpires' => [],
'teams' => [],
]
]
], $overrides);
}
->post(route('games.store', ['week' => $this->week->id]), $this->validParams([
'games' => [
0 => [
'teams' => [1,2]
]
]
]));