PHP: create 2 dimensional array from multidimensional array with value as key - php

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;
}

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"]);

Adding variable to upcomming array

I have a multi dimensional array with some values coming from a foreach, i need to insert this values into the array, but at this moment my result is this, not sure why:
Array
(
[0] => Array
(
[title] => MySecure
)
[1] => Array
(
[productTitle] => My New Product
)
[2] => Array
(
[title] => My Second Company
)
[3] => Array
(
[productTitle] => Another Product
)
[4] => Array
(
[productTitle] => Away Product
)
)
This is wrong, what i need is:
Array
(
[0] => Array
(
[title] => MySecure
[productTitle] => My New Product
)
[2] => Array
(
[title] => My Second Company
[productTitle] => Another Product
[productTitle] => Away Product
)
)
So this is what i have done:
$companies[] = [
'title' => $getCompanie->getTitle()
];
Then inside products :
$companies[] = [
'productTitle' => $getProduct->getTitle(),
];
so i assume im using the wrong array call, not sure about array_push?
You need to add both keys in the same inner array, rather than pushing them separately.
Use nested loops to get all the products associated with a company in the same loop.
$companies = [];
foreach ($all_companies as $companie) {
$products = [];
foreach ($companie->getProducts() as $getProduct) {
$products[] = $getProduct->getTitle());
}
$companies[] = [
'title' => $companie->getTitle(),
'productTitle' => $products
]
}
I've had to make up names for some of the things I assumed are in your code. You should be able to extrapolate from this to your actual design.
$newArray= [
'title' => array_map($yourArray,fn($ar)=>$ar['title']),
'productTitle' => array_map($yourArray,fn($ar)=>$ar['productTitle'])
];

How to move array in multidimensional array using key value?

How to move array in multidimensional aray with key value?
I'm using array_push to add values to a multidimensional array. i have an array
$myArray = Array(Array('code' => '1','room' => Array('name' => 'Room-A')),Array('code' =>'1','room' => Array('name' => 'Room-B'
)), Array('code' => '2','room' => Array('name' => 'Vip-1')),Array('code' => '2','room' => Array('name' => 'Vip-2')));
i tried using code like this:
for ($i=0; $i <count($myArray) ; $i++) {
if ($myArray[$i]['code']=='1') {
array_push($myArray[$i]['room'], $myArray[$i]['room']);
}
else{
array_push($myArray[$i]['room'], $myArray[$i]['room']);
}
}
i want the result like this :
Array
(
[0] => Array
(
[code] => 1
[room] => Array
(
[0] => Array
(
[name] => Room-A
)
[1] => Array
(
[name] => Room-B
)
)
)
[1] => Array
(
[code] => 2
[room] => Array
(
[0] => Array
(
[name] => Vip-1
)
[1] => Array
(
[name] => Vip-2
)
)
)
)
Any idea how to join this array?
You can use array_reduce to summarize the array into an associative array using the code as the key. Use array_values to convert the associative array into a simple array.
$myArray = ....
$result = array_values(array_reduce($myArray, function($c, $v){
if ( !isset( $c[ $v['code'] ] ) ) $c[ $v['code'] ] = array( 'code' => $v['code'], 'room' => array() );
$c[ $v['code'] ]['room'][] = $v['room'];
return $c;
},array()));
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[code] => 1
[room] => Array
(
[0] => Array
(
[name] => Room-A
)
[1] => Array
(
[name] => Room-B
)
)
)
[1] => Array
(
[code] => 2
[room] => Array
(
[0] => Array
(
[name] => Vip-1
)
[1] => Array
(
[name] => Vip-2
)
)
)
)
This is the foreach() equivalent of Eddie's answer (I find it easier to read/maintain).
Code: (Demo)
$myArray = [
['code' => '1', 'room' => ['name' => 'Room-A']],
['code' => '1', 'room' => ['name' => 'Room-B']],
['code' => '2', 'room' => ['name' => 'Vip-1']],
['code' => '2', 'room' => ['name' => 'Vip-2']]
];
foreach ($myArray as $row) {
if (!isset($result[$row['code']])) {
$result[$row['code']] = ['code' => $row['code'], 'room' => [$row['room']]];
// ^------------^-- pushed deeper
} else {
$result[$row['code']]['room'][] = $row['room'];
// ^^-- pushed deeper
}
}
var_export(array_values($result));
This question is very similar to many pre-existing questions that want to group by a particular column. I was not able to find an exact duplicate to close with because the requirement of this question is to created a deeper structure to contain the room sub arrays.
Typically I would write:
if (!isset($result[$row['code']])) {
$result[$row['code']] = $row;
to cut down on syntax, but the new output structure must be applied to both the if and the else.
To avoid key duplication/collision, the room subarrays need to be pushed/indexed to a lower level.
In the end, the technique has been demonstrated here many, many times on StackOverflow. You target an element value to group by and use that value as the temporary key as you iterate the input array. Checking if the temporary keys exist or not is the fastest way to determine if a group is new or previously encountered. When you are done, call array_values() to remove the temporary keys (re-index the array).

Array inside array or nested array

I have an array like below: all the values I am getting one array only, but I don't want this way. This is the best way to do so, in php or jQuery both languages are ok for me
Array
(
[0] => Array
(
[val] => facebook
)
[1] => Array
(
[val] => snapchat
)
[2] => Array
(
[val] => instagram
)
[3] => Array
(
[expenses] => 986532
)
[4] => Array
(
[expenses] => 45456
)
[5] => Array
(
[expenses] => 56230
)
[6] => Array
(
[social_id] => 15
)
[7] => Array
(
[social_id] => 16
)
[8] => Array
(
[social_id] => 17
)
)
and I want to output like this..
$result = array(
array(
"val" => "Facebook",
"expenses" => "84512",
"social_id" => 1
),
array(
"val" => "Instagram",
"expenses" => "123",
"social_id" => 2
)
);
but this should be dynamic, the length of the above array can be varies
You can merge the arrays to one and use array_column to get all vals or expenses in a separate array.
Then foreach one array and build the new array with the key.
//$a = your array
// Grab each column separate
$val = array_column($a, "val");
$expenses= array_column($a, "expenses");
$social_id = array_column($a, "social_id");
Foreach($val as $key => $v){
$arr[] = [$v, $expenses[$key], $social_id[$key]];
}
Var_dump($arr);
https://3v4l.org/nVtDf
Edit updated with the 'latest' version of the array. My code works just fine with this array to without any changes.
to get that array style you can do it by hand for each array
function test(array ...$arr)
{
$result = array();
foreach ($arr as $key => $pair) {
foreach ($pair as $item => $value) {
$result[$item] = $value;
}
}
return $result;
}
$arr1 = test( ['facebook' => 1], ['expenses' => 100]);
print_r($arr1);
/* Array (
[facebook] => 1,
[expenses] => 100
)
*/
$arr2 = test( $arr1, ['more info' => 'info'] );
print_r($arr2);
/* Array (
[facebook] => 1,
[expenses] => 100,
[more info] => info
)
*/
you can pass it any number of
['Key' => 'Pair']
array('Key' => 'Pair')
or even a previous made array and it will add them up into 1 big array and return it

create new array by cutting key from an existing array over to the new array

i want to take an array and cut some of the keys from it (not in order) and create a new array from them.
I have doing it using the array_shift() function, but came to a point where the next key needed to be skipped and then do the array_shift again.
How can I logically tackle this?
my array
Array
(
[api] => Array
(
[0] => system
[1] => assets
[2] => theme
[3] => resources
[4] => api
[5] => xml
[6] => json
[7] => jsonp
[8] => request
)
[class] => Array
(
[name] => authentication
[abbr] => auth
)
[directories] => Array
(
[application] => application
[mvc] => Array
(
[model] => model
[view] => view
[controller] => controller
)
[assets] => Array
(
[folder] => assets
[css] => css
[img] => img
[js] => js
)
[config] => config
)
[smarty] => Array
(
[security] => on
[delimiter] => Array
(
[left] => {!
[right] => !}
)
[template] => Array
(
[header] => header
[footer] => footer
[extension] => tpl
)
)
[version] => Array
(
[component] => Array
(
[0] => Array
(
[name] => CMS
[version] => 1.0
)
[1] => Array
(
[name] => TinyMCE jQuery Package
[version] => 3.5
)
[2] => Array
(
[name] => jQuery
[version] => 1.7.2
)
)
)
)
I need to make a new array from they keys: api, class, version
Create an explicit list of keys that you'd like to move from one array to another. Cycle over that list, pulling from one and adding to another. Then remove the old copy from the original array:
// Original Array, and empty Array
$array = array( 'api' => 1, 'class' => 2, 'fizz' => 3, 'buzz' => 4 );
$newAr = array();
// For each key we'd like to keep
foreach ( array( 'api', 'class' ) as $key ) {
// (Re)move the value from the original array to our new array
$newAr[$key] = $array[$key]; unset( $array[$key] );
}
// Show the contents of the new array
print_r( $newAr );
Try it online now: http://codepad.org/7iYG4iVB
If it's just those 3 keys you need:
$newArray = array(
"api" => $oldArray["api"],
"class" => $oldArray["class"],
"version" => $oldArray["version"]
);
There's array_slice() which lets you 'slice' out a portion of an array. That portion can be a single element, or a range of elements. Basically the slice function lets you hack 'n chop on an array like substr() lets you hack 'n chop up a string.
This seems too simple:
$new_array = array(
'api' => $old_array['api'],
'class' => $old_array['class'],
'version' => $old_array['version']
);
Then do a var_dump( $new_array); to see if it contains the desired output.
$keys = array(1, 5, 'foo');
$new = array();
foreach ($keys as $key) {
$new[$key] = $old[$key];
// or maybe just $new[] = $old[$key];
unset($old[$key]);
}
There's shorter ways to do this, but I think you can understand how this works.
edit - Here's a shorter way
$keys = array(1, 5);
$new = array_intersect_key($old, array_flip($keys)));
$old = array_diff_key($old, array_flip($keys)));

Categories