Group multi array by key and value PHP - php

I have an array like the one below
array:4 [▼
0 => array:3 [▼
0 => array:2 [▼
"url" => "https://domain.com.vn"
"value" => "Keyword B3"
]
1 => array:2 [▼
"url" => "https://domain.com.vn"
"value" => "[IMAGES 1]"
]
]
1 => array:3 [▼
0 => array:2 [▼
"url" => "https://domain-4.com.vn"
"value" => "D1"
]
1 => array:2 [▼
"url" => "https://domain-4.com.vn"
"value" => "E3"
]
]
]
I want to combine the above 2 arrays into 1 array as follows (number of items in 2 arrays is always equal):
$result = [
[
"url" => [
"https://domain.com.vn",
"https://domain-4.com.vn"
]
"value" => [
"Keyword B3",
"D1"
]
],
[
"url" => [
"https://domain.com.vn",
"https://domain-4.com.vn"
],
"value" => [
"[IMAGES 1]",
"E3"
]
]
]
I have searched a lot but have not found a solution yet. Thanks for any help.

Because number of items in 2 sub-arrays is always equal, you can use a for loop like this:
$array = [
0 => [
0 => [
'url' => 'https://domain.com.vn',
'value' => 'Keyword B3'
],
1 => [
'url' => 'https://domain.com.vn',
'value' => '[IMAGES 1]'
]
],
1 => [
0 => [
'url' => 'https://domain-4.com.vn',
'value' => 'D1'
],
1 => [
'url' => 'https://domain-4.com.vn',
'value' => 'E3'
]
]
];
$result = [];
for ($i = 0 ; $i < count($array[0]); $i++) {
$result[] = [
'url' => [$array[0][$i]['url'], $array[1][$i]['url']],
'value' => [$array[0][$i]['value'], $array[1][$i]['value']],
];
}
print_r($result);
Result:
Array
(
[0] => Array
(
[url] => Array
(
[0] => https://domain.com.vn
[1] => https://domain-4.com.vn
)
[value] => Array
(
[0] => Keyword B3
[1] => D1
)
)
[1] => Array
(
[url] => Array
(
[0] => https://domain.com.vn
[1] => https://domain-4.com.vn
)
[value] => Array
(
[0] => [IMAGES 1]
[1] => E3
)
)
)

For a dynamic solution, you will need to iterate the first level of the array, then combine the first deep subarray's keys with the return value of array_map()'s special transposing behavior with null and the spread operator.
It sure is a bunch of voodoo, but it is dynamic.
Code: (Demo) (Demo showing different length first level data sets)
var_export(
array_map(
function ($subarray) {
return array_combine(
array_keys($subarray[0]),
array_map(null, ...array_values($subarray))
);
},
$array
)
);
See other other phptranspose tagged Stack Overflow pages to see other usages of the transposing technique.

Related

Laravel - Can i add new item to an array based on the `id` value existing that array?

array (
0 =>
array (
'courseId' => 14,
'tutorName' => 'admin',
),
1 =>
array (
'courseId' => 15,
'tutorName' => 'merl',
),
)
var_export($response) is an array like above. For each courseId in the $response array, i wanted to find sum of points when the courseId in the $response array exists student_learning table also. After that, i wanted to add this sum of points($points) to the $response array as a new item for the corresponding courseId. Here, the issue is that, every values of $points is added as a new item in every datasets of the $response array,but i wanted it to get added to the $response array of it's respective courseId only. How can i do that?
foreach ($response as $key ) {
$points=DB::table('student_learning')->groupBy('courseId')->where('courseId',$key['courseId'])->sum('points');
$res = array_map(function($e) use($points,$percent) {
$e['points'] = $points;
return $e; }, $response);
dump($res);
}
dump($res) gives an output like below
array:2 [
0 => array:8 [
"courseId" => 14
"tutorName" => "admin"
"points" => 12
]
1 => array:8 [
"courseId" => 15
"tutorName" => "me"
"points" => 12
]
]
array:2 [
0 => array:8 [
"courseId" => 14
"tutorName" => "admin"
"points" => 3
]
1 => array:8 [
"courseId" => 15
"tutorName" => "me"
"points" => 3
]
]
dump($res) outside the foreach gives an output like below
array:2 [
0 => array:8 [
"courseId" => 14
"tutorName" => "admin"
"points" => 3
]
1 => array:8 [
"courseId" => 15
"tutorName" => "me"
"points" => 3
]
]
Expected/Required Output:
[
"courseId" => 14
"tutorName" => "admin"
"points" => 12
]
[
"courseId" => 15
"tutorName" => "me"
"points" => 3
]
You can add new array key while looping using foreach
$response = array (
0 =>
array (
'courseId' => 14,
'tutorName' => 'admin',
),
1 =>
array (
'courseId' => 15,
'tutorName' => 'merl',
),
);
$newResponse = [];
foreach($response as $eachResponse){
$points=DB::table('student_learning')->groupBy('courseId')->where('courseId',$eachResponse['courseId'])->sum('points');
$eachResponse['points'] = $points;
$newResponse[] = $eachResponse;
}
dd($newResponse);

Php array with combination of number of days and number of users

i want to get list of days with respect to number of users. Like, if there is 2 users and based on from and to date, will take number of days to get result array.
i have users array with 2 elements and numbers array with 2 elements. Result array will have 4 elements looks like given below
these are my arrays users can have more elements than days or days can have more elements than users
$users = array:2 [
0 => array:1 [
"id" => "1"
]
1 => array:1 [
"id" => "2"
]
];
$days = array:2 [
0 => array:1 [
"Date" => "01-06-2020"
]
1 => array:1 [
"Date" => "02-06-2020"
]
];
Result array looks like
$result = array: 4[
0 => array:2 [
"Date" => "01-06-2020"
"User" => "1"
]
1 => array:2 [
"Date" => "02-06-2020"
"User" => "1"
]
2 => array:2 [
"Date" => "01-06-2020"
"User" => "2"
]
3 => array:2 [
"Date" => "02-06-2020"
"User" => "2"
]
]
How can i get this result using foreach
I tried with this
foreach ($users as $key=>$user) {
foreach($days as $val) {
$result[$key]['Date'] = $val->Date;
$result[$key]['User'] = $user->id;
}
}
You confuse arrays and objects. The data you posted as input data is arrays of arrays, not arrays of objects. So you need to access array elements inside your loops, not object properties as you try to:
<?php
$users = [
[ "id" => "1" ],
[ "id" => "2" ]
];
$days = [
[ "Date" => "01-06-2020" ],
[ "Date" => "02-06-2020" ]
];
$result = [];
foreach($users as $user) {
foreach ($days as $day) {
$result[] = [
"Date" => $day["Date"],
"User" => $user["id"]
];
}
}
print_r($result);
The output obviously is:
Array
(
[0] => Array
(
[Date] => 01-06-2020
[User] => 1
)
[1] => Array
(
[Date] => 02-06-2020
[User] => 1
)
[2] => Array
(
[Date] => 01-06-2020
[User] => 2
)
[3] => Array
(
[Date] => 02-06-2020
[User] => 2
)
)

Map Array in child in php

I have 2 arrays in php which look like following:
array1 = [product_id = [data], product_id = [data], ..]
[
101 => [
"sku" => "AB01"
],
201 => [
"sky" => "AB02"
],
...
]
array2 = attribute of product with product_id
[
0 => [
"product_id" => 101,
"name" => "pro 1"
],
1 => [
"product_id" => 101,
"size" => "S"
],
2 => [
"product_id" => 201,
"name" => "pro 2"
],
3 => [
"product_id" => 201,
"size" => "S"
],
...
]
What I want is according to product_id in array2 data is pushed in array1 as child array like this
[
101 => [
"sku" => "AB01",
"attributes" => [
0 => [
"product_id" => 101,
"name" => "pro 1"
],
1 => [
"product_id" => 101,
"size" => "S"
]
]
],
201 => [
"sky" => "AB02",
"attributes" => [
0 => [
"product_id" => 201,
"name" => "pro 2"
],
1 => [
"product_id" => 201,
"size" => "S"
]
]
],
...
]
Array length is around 1000 for array1 and >5000 for array2. foreach loop taking too much time. Is there any fast way to achieve it?
About the fastest way I can think of achieving this is using a foreach loop over the second array, as your first array is indexed by the product_id, it is easy to directly insert the new data on each loop...
foreach ( $array2 as $item ) {
$array1[$item['product_id']]['attributes'][] = $item;
}
Maybe it helps you
$array1 = [
101 => [
"sku" => "AB01"
],
201 => [
"sky" => "AB02"
]
];
$array2 = [
0 => [
"product_id" => 101,
"name" => "pro 1"
],
1 => [
"product_id" => 101,
"size" => "S"
],
2 => [
"product_id" => 201,
"name" => "pro 2"
],
3 => [
"product_id" => 201,
"size" => "S"
]
] ;
foreach ($array2 as $result){
if(array_key_exists($result['product_id'], $array1)) {
$array1[$result['product_id']]['attributes'][] = $result;
}
}
print_r($array1);
your result look like this
Array
(
[101] => Array
(
[sku] => AB01
[attributes] => Array
(
[0] => Array
(
[product_id] => 101
[name] => pro 1
)
[1] => Array
(
[product_id] => 101
[size] => S
)
)
)
[201] => Array
(
[sky] => AB02
[attributes] => Array
(
[0] => Array
(
[product_id] => 201
[name] => pro 2
)
[1] => Array
(
[product_id] => 201
[size] => S
)
)
)
)
$arr1=[
101 => [
"sku" => "AB01"
],
201 => [
"sky" => "AB02"
]
];
$arr2=[
0 => [
"product_id" => 101,
"name" => "pro 1"
],
1 => [
"product_id" => 101,
"size" => "S"
],
2 => [
"product_id" => 201,
"name" => "pro 2"
],
3 => [
"product_id" => 201,
"size" => "S"
]
];
foreach ($arr2 as $arr_val ) {
$arr1[$arr_val['product_id']]['attributes'][] = $arr_val;
}
echo "<pre>"; print_r($arr1);
I hope this answer work for you
first array
$arr = [
101 => [
"sku" => "AB01"
],
201 => [
"sky" => "AB02"
],
];
second array
$arr2 = [
0 => [
"product_id" => 101,
"name" => "pro 1"
],
1 => [
"product_id" => 101,
"size" => "S"
],
2 => [
"product_id" => 201,
"name" => "pro 2"
],
3 => [
"product_id" => 201,
"size" => "S"
],
];
finally this what i try to do
$newArr = [];
forEach($arr as $product_id => $product_value){
$attrArr = [];
forEach($arr2 as $key => $value){
if($product_id == $value['product_id']){
$attrArr[] = $value;
$newArr[$product_id] = [
array_keys($product_value)[0] => array_values($product_value)[0],
];
}
}
$newArr[$product_id]['attributes'] = $attrArr;
}
echo '<pre>';
print_r($newArr);
echo '</pre>';

php - Convert array to an array

I have an array like below:
array:3 [▼
"_token" => "hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso"
"room_id" => array:3 [▼
0 => "089a6ca8-26de-3ca2-bbbf-17c410d15266"
1 => "13c56ac2-6c77-3ca7-b24a-2a70f4f0526c"
2 => "2d9b7392-aa50-37e4-882a-804affb87223"
]
"new_electric" => array:3 [▼
0 => "123"
1 => "234"
2 => "345"
]
]
How can I slice it into new array which like
array:4 [▼
"_token" => "hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso"
"1" => array:2 [▼
"room_d" => "089a6ca8-26de-3ca2-bbbf-17c410d15266"
"new_electric => "123"
]
"2" => array:2 [▼
"room_id" => "13c56ac2-6c77-3ca7-b24a-2a70f4f0526c"
"new_electric" => "234"
]
"3" => array:2 [▼
"room_id" => "2d9b7392-aa50-37e4-882a-804affb87223"
"new_electric" => "345"
]
]
I think I need to use an array_push but I don't know how to do that ? Please help.
You have to use foreach
$arr = array(
"_token" => "hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso",
"room_id" => array(
0 => "089a6ca8-26de-3ca2-bbbf-17c410d15266",
1 => "13c56ac2-6c77-3ca7-b24a-2a70f4f0526c",
2 => "2d9b7392-aa50-37e4-882a-804affb87223",
),
"new_electric" => array(
0 => "123",
1 => "234",
2 => "345",
)
);
$final = array();
$final[ "_token" ] = $arr[ "_token" ];
foreach( $arr[ "room_id" ] as $key => $value ) {
$final[ ( $key + 1 ) ] = array(
"room_id" => $value,
"new_electric" => $arr[ "new_electric" ][ $key ]
);
}
This will result to:
Array
(
[_token] => hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso
[1] => Array
(
[room_id] => 089a6ca8-26de-3ca2-bbbf-17c410d15266
[new_electric] => 123
)
[2] => Array
(
[room_id] => 13c56ac2-6c77-3ca7-b24a-2a70f4f0526c
[new_electric] => 234
)
[3] => Array
(
[room_id] => 2d9b7392-aa50-37e4-882a-804affb87223
[new_electric] => 345
)
)
Note: Use $key + 1 because you want the index to start from 1
You can use array_map with no callback for that (check example #4 in the manual for more detail):
$result = array_map(null, $arr["room_id"], $arr["new_electric"]);
$result['_token'] = $arr['_token'];
other way
<pre>
<?php
$array=array(3=>array("_token"=>"hLuF5TLimRRkxRUOeeWoOby7iXLNXU7EiHRmTAso","room_id"=>array("0"=>"089a6ca8-26de-3ca2-bbbf-17c410d15266"
,"1"=>"13c56ac2-6c77-3ca7-b24a-2a70f4f0526c","2"=>"50-37e4-882a-804affb87223"),"new_electric"=>array(0=>"123","1"=>"234","2"=>"345")));
print_r($array);
$i=0;
$array4=array();
array_push($array4,$array[3]["_token"]);
foreach($arr2 as $value){
array_push($array4,array($array[3]["room_id"][$i],$array[3]["new_electric"][$i]));
$i++;
}
print_r($array4);
?>
</pre>

how to sort array data in alphabetic key order in php

my collection of data in array which is shown below the index key is A,B,C but i want to store these key in "key" and its key letter's words in "dishes" key
array:3 [
"A" => array:4 [
0 => 37
1 => "Algerian"
2 => 6
3 => "American"
]
"B" => array:6 [
0 => 27
1 => "Belgian"
2 => 20
3 => "Brazilian"
]
and so on..
i wanna sort this array like aplhabetic order as shown below
array:10 [
0 => array:2 [
"key" => "A"
"dishes" => array:2 [
0=>array:2[
"id" => 37
"type" => "Algerian"
],
1=>array:2[
"id" => 6
"type" => "American"
]
]
]
1 => array:2 [
"key" => "B"
"dishes" => array:2 [
0=>array:2[
"id" => 27
"type" => "Belgian"
],
1=>array:2[
"id" => 20
"type" => "Brazilian"
]
]
]
and so on...
This would be a possible solution:
<?php
$input = [
'A' => [
0 => 37,
1 => "Algerian",
2 => 6,
3 => "American"
],
'B' => [
0 => 27,
1 => "Belgian",
2 => 20,
3 => "Brazilian"
]
];
$output = [];
array_walk($input, function($values, $key) use (&$output) {
$entry = [
'key' => $key,
'dishes' => []
];
foreach(array_chunk($values, 2) as $chunk) {
$entry['dishes'][] = [
'id' => $chunk[0],
'type' => $chunk[1]
];
}
$output[] = $entry;
});
print_r($output);
The output of above code obviously is:
Array
(
[0] => Array
(
[key] => A
[dishes] => Array
(
[0] => Array
(
[id] => 37
[type] => Algerian
)
[1] => Array
(
[id] => 6
[type] => American
)
)
)
[1] => Array
(
[key] => B
[dishes] => Array
(
[0] => Array
(
[id] => 27
[type] => Belgian
)
[1] => Array
(
[id] => 20
[type] => Brazilian
)
)
)
)
You have to loop through the original array to create your new structure. Then you can use the ksort function to sort them.
$newArr = new array();
for ($arr as $elem) {
$dishArr = new array();
for($elem['dishes'] as $dish) {
$dishArr[] = $dish['id'];
$dishArr[] = $dish['type'];
}
$newArr[$elem['key']] = $dishArr;
}
ksort($newArr);

Categories