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"]);
Related
I've tried some solutions from:
In PHP, how do you change the key of an array element?
php array from multidimensional array keys values
But its is not exacly what i need, i tried to mix some solutions but notting helped.
I have an array from my database:
Array (
[0] => Array (
[ID] => 1
[USER_ID] => 1
[DATA] => UNIQUE
[VALUE] => buuu )
[1] => Array (
[ID] => 2
[USER_ID] => 1
[DATA] => NICKNAME
[VALUE] => NoAd ) )
And i want to transform that database to:
Array (
[UNIQUE] => buuu
[NICKNAME] => NoAd
[any new [2]...[3]... from previous array
after that code:
foreach($playerdata as $segment){
foreach($segment as $key => $value ){
$newArray[$value] = $value;
}
}
my array looks like:
Array ( [UNIQUE] => UNIQUE
[buuu] => buuu
[NICKNAME] => NICKNAME
[NoAd] => NoAd )
i tried use 3x foreach but it ends in error all time i think i need to change some variables in my foreach but no idea how.
Now that I see the other answers it seems it's array_column you are looking for.
It returns an array column and the third parameter is what the key name should be.
$player_data = array(array(
"ID" => 1,
"USER_ID" => 1,
"DATA" => "UNIQUE",
"VALUE" => "buuu"
),
array(
"ID" => 1,
"USER_ID" => 1,
"DATA" => "NICKNAME",
"VALUE" => "NoAd"
));
$new = array_column($player_data, "VALUE", "DATA");
var_dump($new);
Output:
array(2) {
["UNIQUE"]=>
string(4) "buuu"
["NICKNAME"]=>
string(4) "NoAd"
}
https://3v4l.org/ZAkgZ
There is no need for loops to solve this.
lets assume $playerdata has the below values
Array (
[0] => Array (
[ID] => 1
[USER_ID] => 1
[DATA] => UNIQUE
[VALUE] => buuu )
[1] => Array (
[ID] => 2
[USER_ID] => 1
[DATA] => NICKNAME
[VALUE] => NoAd ) )
[2]----
[3]----
$newArray = [];
foreach($playerdata as $record) {
$newArray[$record['DATA']] = $record['DATA'];
$newArray[$record['VALUE']] = $record['VALUE'];
}
print_r($newArray);
You could try something like the following:
$newArray = array();
foreach($playerdata as $segment){
$newArray[$segment['DATA']] = $segment['VALUE'];
}
This code gets the DATA as key and VALUE as value from each part of the array and stores it in $newArray.
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,
),
),
)
I try to create a new array from an complex array.
If there's no easy solution, every hint would help to search more successful.
I have this complex array (shortened a lot) and want to build a new 2 dimensional array:
array (
[key1] => value1
[key2] => value2
[category] => array (
[key3] => value3
[key4] => array (
[small] => value6
[large] => value7
)
[items] => array (
[0] => array (
[aTag] => #PU2RRL
[name] => 3PL
[position] => 25
[versions] => array (
[0] => array (
[bTag] => #KF67RL
[color] => blue
[id] => 001
)
[1] => array (
[bTag] => #Z8TR4
[color] => red
[id] => 002
)
)
)
[1] => array (
...
This is the array I want to create:
array(
[001] => array (
[aTag] => #PU2RRL
[name] => 3PL
[position] => 25
[bTag] => #KF67RL
[color] => blue
)
[002] => array (
[aTag] => #PU2RRL
[name] => 3PL
[position] => 25
[bTag] => #Z8TR4
[color] => blue))
With ID as key and this values:
$itemAll = array(
$array[category][items][0][versions][0][id] => array(
"aTag" => $array[category][items][0][aTag],
"name" => $array[category][items][0][name],
"position" => $array[category][items][0][position],
"bTag" => $array[category][items][0][versions][0][bTag],
"color" => $array[category][items][0][versions][0][color],
)
);
I have no clue how to create this array with foreach loops for "items" and versions with the ID as primary key, any hints?
EDIT: huge thanks to #DeeDuu! Because I had multiple items I added another foreach:
$new_array = array();
// i have multiple items, so I removed [0]:
$items = $array["category"]["items"];
// added another foreach
foreach ($items as $item) {
// changed $items to $item
$shared_properties = array(
"aTag" => $item["aTag"],
"name" => $item["name"],
"position" => $item["position"]
);
// changed $items to $item
foreach ($item["versions"] as $version) {
$specific_properties = array(
"bTag" => $version["bTag"],
"color" => $version["color"]
);
$new_entry = array_merge(
$shared_properties,
$specific_properties
);
$new_array[$version["id"]] = $new_entry; }}
If I understand correctly what you want, something like the following should work.
// This is the target array where we will save the recombinated data
$new_array = array();
// Store the relevant subarray in a new variable;
// This makes the subsequent code shorter
$items = $array["category"]["items"][0];
// This gives the data that will be common to all the new entries,
// for all versions seem to share aTag, name and position
$shared_properties = array(
"aTag" => $items["aTag"],
"name" => $items["name"],
"position" => $items["position"]
);
// Alright, let's loop over the versions
foreach ($items["versions"] as $version) {
// Another array for the data that is specific
// to the version we're currently looking at
$specific_properties = array(
"bTag" => $version["bTag"],
"color" => $version["color"]
);
// The new entry is a combination of the shared and the
// specific properties; array_merge will do that for us
$new_entry = array_merge(
$shared_properties,
$specific_properties
);
// Now add to the new array
$new_array[$version["id"]] = $new_entry;
}
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)
);
I've an following array called $title:
Array
(
[pt_id] => 4
[pt_doc_title] => Solapur IT Park
[pt_doc_id] => 1
[delete_flag] =>
[pt_doc_file_iname] => Array.php
)
But I want this array in below form:
Array
(
[0] => Array
(
[pt_doc_id] => 1
[pt_id] => 4
[pt_doc_title] => Solapur IT Park
[pt_doc_file_iname] =>
[pt_doc_added_date] => 1390390546
[pt_doc_updated_date] => 1390390704
)
)
How can I achieve this? Though here array key is zero I'm having another key values in my hand. The issue I'm facing is how to add these key numbers (as 0 is added above)? Please help.
save your array in this format.
$title = array();
$title[] = array(
'pt_doc_id'=>'1',
'pt_id'=>'4',
'pt_doc_title'=>'Solapur IT Park',
'pt_doc_file_iname'=>'',
'pt_doc_added_date'=>'1390390546',
'pt_doc_updated_date'=>'1390390704'
);
set your array format like this.
i hop this is working.
Suppose your array1 & array2
<?php
$array1=Array
(
'pt_id' => '4',
'pt_doc_title' => 'Solapur IT Park'
);
$array2[0]=$array1;
print_r($array2);
?>
Will give you output:
Array
(
[0] => Array
(
[pt_id] => 4
[pt_doc_title] => Solapur IT Park
)
)
Live demo : https://eval.in/93311
use array_push it will auto indexing your array. if you have multi-dimensional array then you can run this steps in a loop.
$arr =array
(
"pt_id" => 4,
"pt_doc_title" =>" Solapur IT Park",
"pt_doc_id" => 1,
"delete_flag" => '',
"pt_doc_file_iname" => "Array.php"
);
$arr['pt_doc_added_date'] = 1390390546; //add your new element
$arr['pt_doc_updated_date'] = 1390390704;
$result = array();
array_push($result,$arr); //push this array in result array
print_r($result);
OUTPUT:
Array
(
[0] => Array
(
[pt_id] => 4
[pt_doc_title] => Solapur IT Park
[pt_doc_id] => 1
[delete_flag] =>
[pt_doc_file_iname] => Array.php
[pt_doc_added_date] => 1390390546
[pt_doc_updated_date] => 1390390704
)
)