Combine multiple array with one array key - php

I have a situation in PHP where I need to combine multiple array values and bind with the first array key, Let say I have following array,
[services] => Array
(
[0] => 1
[1] => 2
[2] => 1
)
[package_type] => Array
(
[0] => 1
[1] => 2
[2] => 1
)
[service_desc] => Array
(
[0] => Full HD
[1] => Full HD
[2] => Full HD
)
[service_price] => Array
(
[0] => 500
[1] => 600
[2] => 500
)
Now , I want to bind all array with service type keys like services[0] will have the value of package_type[0], service_desc[0] and service_price[0]. The purpose is that I can easily identify all service related values with its Id. Can anyone suggest ?

array_map is key here. Leave the first argument as null and it will group as you want:
<?php
$data =
[
'services' =>
[
'programming',
'debugging'
],
'description' =>
[
'the process of writing computer programs.',
'the process of identifying and removing errors from software/hardware'
]
];
$result = array_map(null, $data['services'], $data['description']);
var_export($result);
Output:
array (
0 =>
array (
0 => 'programming',
1 => 'the process of writing computer programs.',
),
1 =>
array (
0 => 'debugging',
1 => 'the process of identifying and removing errors from software/hardware',
),
)
Instead of writing out all your keys as arguments you could unpack like this:
array_map(null, ...array_values($data));
For something more elaborate, pass array_map a callable:
$keys = array_keys($data);
$result = array_map(function(...$args) use ($keys) {
return array_combine($keys, $args);
}, ...array_values($data));
var_export($result);
Output:
array (
0 =>
array (
'services' => 'programming',
'description' => 'the process of writing computer programs.',
),
1 =>
array (
'services' => 'debugging',
'description' => 'the process of identifying and removing errors from software/hardware',
),
)

Related

split one array have two key split into two array in php

Question :
I have one array have two key or more split into two or more create array based on array in php.
my Array :
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I want output like this :
output:
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
)
)
array(
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I am not sure how you want to store those arrays, but let me help you.
I assume you have a datastructure like this, so one array with multiple values.
array (
key1 => ...values...,
key2 => ...values...,
...
key_n => ...values...
)
And you want something like this, si multiple arrays with single keys well you need to store that array somehow.
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
If you do not know the exact number of arrays, you can't $array1, $array2, ... $array_n and it also not efficent, so you shoudl have an array of arrays. So something like this:
array(
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
)
So you should iterate trough the keys of the input array and then
So the code
<?php
//example input array
$arr = array (
"key1" => "val1",
"key2" => "val2"
);
$keys = array_keys($arr); //get the keys of the input array, see phpdoc
$output = [];
foreach($keys as $key) {
$output[] = array ($arr[$key]);
}
?>
This will output an array of arrays, with single key of the inner array.
If this is not you answer, reply.
Research:
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/control-structures.foreach.php
php.net - arrays manual Example #6 Accessing array elements
Maybe this document will help you
This may also help you
<?php
$stdArray = array(
"foo" => "bar",
42 => 24,
"dimensional" => array(
"fname" => "jon",
"lname" => "doe",
),
"multi" => array(
"RAJAHMUNDRY" => array(
"unspcp_code" => 46182005,
"head_quarter" => "RAJAHMUNDRY",
0 => 2
),
"HYDERABAD" => array(
"unspcp_code" => 46182005,
"head_quarter" => "HYDERABAD",
0 => 2
),
)
);
print_r($stdArray);
print_r($stdArray["multi"]);
print_r($stdArray["multi"]["RAJAHMUNDRY"]);

Summarize the same key name in php multidimensional array

I have an array like this:
[0] => Array
(
[id_station] => 2397
[hour] => 12
[data] => Array
(
[cameraon] => 355654
[cameraoff] => 4532
[camerabroken] => 76745
...
)
)
[1] => Array
(
[id_station] => 2399
[hour] => 13
[data] => Array
(
[cameraon] => 3905466
[cameraoff] => 1672
[camerabroken] => 70780
...
)
)
I want to add one more row = total of all items
[1] => Array
(
[id_station] =>
[hour] =>
[data] => Array
(
[cameraon] => 4261120
[cameraoff] => 6204
[camerabroken] => 147525
)
)
I used array_sum(array_column($array["data], 'cameraon')) but I have to do for all items cameraon, cameraoff, camerabroken (I have a hundred items).
Is there any way to get total row in this case?
I assume that you don't know the depth of data sub-array. (that is how many key-value pairs are there)
So do like below:-
$final_array = [];
$final_array['id_station'] ='';
$final_array['hour'] ='';
foreach($original_array as $original_arr){
foreach($original_arr['data'] as $key=>$original){
$final_array['data'][$key] +=$original;
}
}
Output:-https://eval.in/926729
You wish to sum the columnar data, so leveraging array_sum() and array_column() are wise choices. The only thing left to do is set up the loop.
You can first isolate the data subarrays using array_column() then "drill down" into the first subarray to iterate each column. Use the column names to access all values in all columns. This makes the method dynamically successful regardless of the complexity of your data subarrays.
Code: (Demo)
$array=[
[
'id_station'=>2397,
'hour'=>12,
'data'=>['cameraon'=>355654,'cameraoff'=>4532,'camerabroken'=>76745]
],
[
'id_station'=>2399,
'hour'=>14,
'data'=>['cameraon'=>3905466,'cameraoff'=>1672,'camerabroken'=>70780]
]
];
$datas=array_column($array,'data'); // isolate the data subarrays
foreach(current($datas) as $column=>$data){ // iterate the columns
$result[$column]=array_sum(array_column($datas,$column)); // sum the column values
}
$array[]=['id_station'=>'','hour'=>'','data'=>$result]; // completenew item and append
var_export($array); // print to screen
Output:
array (
0 =>
array (
'id_station' => 2397,
'hour' => 12,
'data' =>
array (
'cameraon' => 355654,
'cameraoff' => 4532,
'camerabroken' => 76745,
),
),
1 =>
array (
'id_station' => 2399,
'hour' => 14,
'data' =>
array (
'cameraon' => 3905466,
'cameraoff' => 1672,
'camerabroken' => 70780,
),
),
2 =>
array (
'id_station' => '',
'hour' => '',
'data' =>
array (
'cameraon' => 4261120,
'cameraoff' => 6204,
'camerabroken' => 147525,
),
),
)

Convert Multidimensional arrays as key and value in PHP

I have 2 Multidimensional arrays as follow:
Array1:
Array (
[0] => Array (
[0] => 2D Design
[1] => 3D Design & Modeling)
[1] => Array ( [0] => Android Developer
[1] => Artificial Intelligence
[2] => Web Developer)
)
Array2:
Array (
[0] => Array (
[0] => 5
[1] => 10)
[1] => Array ( [0] => 2
[1] => 4
[2] => 6)
)
I want to combine the above 2 arrays as key and value as below.
Array (
[0] => Array (
[2D Design] => 5
[3D Design & Modeling] => 10 )
[1] => Array (
[Android Developer] => 2
[Artificial Intelligence] => 4
[Web Developer] => 6 )
)
Please help me to do this. Answers will be appreciated.
use array_combine() function creates an array by using the elements from one "keys" array and one "values" array.
Note: Both arrays must have equal number of elements!
First parameter array taken as key of new array and second parameter taken as value new array .
$new_array=array();
for($i=0;$i<count($arr1);$i++)
{
$new_array[$i]=array_combine($arr1[$i],$arr2[$i]);
}
print_r($new_array);
Output :
Array
(
[0] => Array
(
[2D Design] => 5
[3D Design & Modeling] => 10
)
[1] => Array
(
[Android Developer] => 2
[Artificial Intelligence] => 4
[Web Developer] => 6
)
)
This will work,
$arr1 = array(
0 => array(
0 => "2D Design",
1 => "3D Design & Modeling"),
1 => array(0 => "Android Developer",
1 => "Artificial Intelligence",
2 => "Web Developer",
),
);
$arr2 = array(
0 => array(
0 => 5,
1 => 10,
),
1 => array(0 => 2,
1 => 4,
2 => 6,
),
);
$temp = [];
foreach ($arr1 as $k => &$v) {
foreach ($v as $k1 => &$v1) {
$temp[$k][$v1] = $arr2[$k][$k1];
}
}
print_r($temp);
I have fetched values of first array arr1 as key to temp variable and map it with values of arr2as value to temp array.
This code will work even if index i.e. 0,1,2,3 can be anything.
Here is working code.
Simply make mapped calls of array_combine(). So long as the same positioned rows have the same number of elements in them, everything will work perfectly.
Code: (Demo)
$keys =[
['2D Design', '3D Design & Modeling'],
['Android Developer', 'Artificial Intelligence', 'Web Developer']
];
$values = [
[5, 10],
[2, 4, 6]
];
var_export(
array_map('array_combine', $keys, $values)
);

explode string to a multi array with 2 delimiter

I have this kind of sting i variable in php:
$hccRol = GA#COR,OP#COR,FOR#TB,GA#LTS,FOR#MOD,GA#PMAI,LDR#LID,HCC#LAD,HN#LAD,OP#LAD,GA#LAD,GA#WM,OP#WM,HN#WM,OP#VZ,HN#VZ,GA#VZAI
I want convert this to multi array that look somthing like this:
Array ( [GA] => Array ( [1] => COR
[2] => LTS
[3] => LAD
[4] => WM
[5] => VZAI
)
[FOR] => Array( [1] => TB
[2] => MOD
)
[OP] => Array( [1] => COR
[2] => WM
[3] => VZ
)
)
So the # determines in witch primary array the value must come
CBroe gave you the steps to do it the traditional way, so just for fun because I was bored:
parse_str(str_replace(array('#',','), array('[]=','&'), $hccRol ), $result);
print_r($result);
PHP >= 5.4.0:
parse_str(str_replace(['#',','], ['[]=','&'], $hccRol ), $result);
The following is a basic way to explode on the delimiting characters, iterate the data, and declare the new array structure. I will honor your desired output and start the keys at 1 instead of the standard 0.
Code: (Demo)
$hccRol = "GA#COR,OP#COR,FOR#TB,GA#LTS,FOR#MOD,GA#PMAI,LDR#LID,HCC#LAD,HN#LAD,OP#LAD,GA#LAD,GA#WM,OP#WM,HN#WM,OP#VZ,HN#VZ,GA#VZAI";
foreach (explode(",", $hccRol) as $item) {
$halves = explode("#", $item, 2);
if (!isset($result[$halves[0]])) {
$result[$halves[0]][] = null; // add zero key placeholder element
}
$result[$halves[0]][] = $halves[1];
unset($result[$halves[0]][0]); // remove the placeholder element
}
var_export($result);
Output:
array (
'GA' =>
array (
1 => 'COR',
2 => 'LTS',
3 => 'PMAI',
4 => 'LAD',
5 => 'WM',
6 => 'VZAI',
),
'OP' =>
array (
1 => 'COR',
2 => 'LAD',
3 => 'WM',
4 => 'VZ',
),
'FOR' =>
array (
1 => 'TB',
2 => 'MOD',
),
'LDR' =>
array (
1 => 'LID',
),
'HCC' =>
array (
1 => 'LAD',
),
'HN' =>
array (
1 => 'LAD',
2 => 'WM',
3 => 'VZ',
),
)
If you are happy to have the 0 indexes, then just remove the if{} block and the unset() line.

smaller array based on array contents

I am looking for a way to create a new array based on array contents.
so i've got:
Array ( [0] => 1
[type] => first_value_i_need
[some_id] => 2
[hits] => 88
[some_other_id] => second_value_i_need
)
and i would like to get
Array ( [0] => 1
[app_name] => "first_value_i_need-second_value_i_need"
[hits] => "88"
)
I know that i need some sort of foreach function, but i'm right now lost.
No, you don't need any loops as long as you know which keys you need.
$old = array(
0 => 1,
'type' => 'first_value_i_need',
'some_id' => 2,
'hits' => 88,
'some_other_id' => 'second_value_i_need'
);
$new = array(
0 => $old[0],
'app_name' => $old['type'].'-'.$old['some_other_id'],
'hits' => $old['hits'],
);
So basically do you wnat to get rid of the app_table_id key ?
You can do unset($array['app_table_id']);
And if you need to change some value you can do :
$array['app_name'] = $array['some_other_id'];
//> Note i posted this before your edit.

Categories