PHP add keys to nested arrays - php

I have nested arrays that do not have keys. I want to add keys in a particular order. What is a clean way to do this?
Start with this array. It is only indexed by position.
[0] => (
[0] => Tyler
[1] => Durden
[2] => 05/07/1985
)
[1] => (
[0] => Edward
[1] => Norton
[2] => 03/21/1988
)
Now apply these keys in order:
['first_name'] =>
['last_name'] =>
['birthday'] =>
Final array:
[0] => (
['first_name'] => Tyler
['last_name'] => Durden
['birthday'] => 05/071985
)
[1] => (
['first_name'] => Edward
['last_name'] => Norton
['birthday'] => 03/21/1988
)
Bonus upvotes if your code allows for any key structure, instead of being hard-coded!

I think array_combine will do the trick:
foreach ($bigarray as &$x) {
$x = array_combine(array('first_name','last_name','birthday'),$x);
}

Also the classic algorythm:
foreach ( $array as $key=>$value ) {
$array[$key]['first_name'] = $array[$key][0];
$array[$key]['last_name'] = $array[$key][1];
$array[$key]['birthday'] = $array[$key][2];
unset($array[$key][0]);
unset($array[$key][1]);
unset($array[$key][2]);
}

Related

How to create an array with the values of a nested array?

I have a multi-dimensional array that looks like this:
Array
(
[0] => Array
(
[name] => nonce
[value] => 4OdIiR6JhZ,1565652176,9c1abd8d4e7c717bb1c8a27552aabce58b3bf4b3
)
[1] => Array
(
[name] => firstName
[value] => Honkey
)
[2] => Array
(
[name] => lastName
[value] => McDonalds
)
)
and I want to get an array that looks like this:
Array
(
[nonce] => 4OdIiR6JhZ,1565652176,9c1abd8d4e7c717bb1c8a27552aabce58b3bf4b3
[firstName] => Honkey
[lastName] => McDonalds
)
I know that I could accomplish this by doing a foreach loop and creating a new array.
$newForm = [];
foreach ($something as $index => $item) {
$newIndex = $item['name'];
$newForm[$newIndex] = $item['value'];
}
But I am wondering if there is a better way to do this (perhaps using one of PHP's array functions)?
This is what the 3 parameter form of array_column is perfect for:
$output = array_column($input, 'value', 'name');
Output:
Array
(
[nonce] => 4OdIiR6JhZ,1565652176,9c1abd8d4e7c717bb1c8a27552aabce58b3bf4b3
[firstName] => Honkey
[lastName] => McDonalds
)
Demo on 3v4l.org
With foreach,
$result = [];
foreach($array as $v){
$result[$v["name"]] = $v["value"];
}
Check Demo

Remove duplicate data based on postID

I have an array which is as follows:
Array
(
[0] => Array
(
[postId] => 105
[postTitle] => Test
[postNonArray] => Subzero
[postDesc] => Array
(
[0] => Array
(
[para] => Subzero
[align] => L
)
)
[postDate] => 25.08.2016
[postTime] => 13:44
[postImage] => http://testyourprojects.biz/custom/ci/tharjumal/uploads/post/post_1472112857.png
[postVideo] =>
)
[1] => Array
(
[postId] => 106
[postTitle] => Test 2
[postNonArray] => Test
[postDesc] => Array
(
[0] => Array
(
[para] => Test
[align] => L
)
)
[postDate] => 26.08.2016
[postTime] => 18:08
[postImage] => http://testyourprojects.biz/custom/ci/tharjumal/uploads/post/post_1472215085.jpg
[postVideo] =>
)
[2] => Array
(
[postId] => 106
[postTitle] => Test 2
[postNonArray] => Test
[postDesc] => Array
(
[0] => Array
(
[para] => Test
[align] => L
)
)
[postDate] => 26.08.2016
[postTime] => 18:08
[postImage] => http://testyourprojects.biz/custom/ci/tharjumal/uploads/post/post_1472215085.jpg
[postVideo] =>
)
)
As you can see, there is two post details with postId=106;
How can I remove the redundant data from the array based on postId?
The project is on PHP.
I think this is what you are trying to achieve:-
$array = array_map("unserialize", array_unique(array_map("serialize", $array)));
echo "<pre/>";print_r($array);
Check output(whole code with your original array):- https://eval.in/630678
Note:- It will remove the duplicate values (so whole duplicate array will gone as you asked in comment)
I would suggest loop like the one below. It will go through all the elements from $your_array_name and will make an unique array of id where we will store the postIds. We will also check if there are duplicated in the $unique_ids array, and if so we will remove that duplicate element.
$unique_ids = array();
foreach($your_array_name as $key => $value){
//check if the postId is in the array of the unique ids
if(!in_array($value['postId'], $unique_ids)()){
array_push($unique_ids,$value['postId']); //if it is not - push it there
} else {
unset($your_array_name($key)); //if it is - remove the whole element from the array
}
}
You will need to loop the data and create a new array with unique values so here you go:
$ShowNewArray = array();
foreach($array as $key => $value){
if(!array_key_exists('postId', $ShowNewArray)){
$ShowNewArray[$value['postId']] = $value;
}
}
print_r($ShowNewArray);
Hope it will help you.

How to merge Arrays having same keys only and neglect different keys?

I am new in PHP and love to learn it.
I want to merge two or more arrays having same keys only. And neglect the arrays whose keys are not in both the Arrays. Like
Here is the First Array :
Array
(
[1] => Array
(
[111] => 36265
)
[2] => Array
(
[222] => 36265
)
[3] => Array
(
[333] => 36265
)
)
and Second Array as :
Array
(
[1] => Array
(
[444] => 36265
)
[2] => Array
(
[555] => 36265
)
[4] => Array
(
[666] => 36265
)
)
And i want my result to be as :
Array
(
[1] => Array
(
[111] => 36265
[444] => 36265
)
[2] => Array
(
[222] => 36265
[555] => 36265
)
)
Neglecting the rest Array with key [3] & [4]....
So Please anyone tell me how to get this. I try out "array_merge_recursive()" but this one displays all keys.
Thanks in advance.
You'd have to loop over one of the arrays, check for the existence of the current key in the other array, if it exists, merge them, eg:
$output = array();
foreach ($array1 as $key => $value) {
if (array_key_exists($key, $array2)) {
$output[$key] = $value + $array2[$key];
}
}
Here's a demo
You're probably looking for array_intersect_key.
You could also use a foreacah loop and create a new one. While in this loop you can use one of the arrays keys to match them both. Consider this example:
$array1 = array( 1 => array(111 => 36265), 2 => array(222 => 36265), 3 => array(333 => 36265), ); $array2 = array( 1 => array(444 => 36265), 2 => array(555 => 36265), 4 => array(666 => 36265), );
$new_array = array();
foreach($array1 as $key => $value) {
if(isset($array2[$key])) {
$new_array[$key][key($array1[$key])] = reset($array1[$key]);
$new_array[$key][key($array2[$key])] = reset($array2[$key]);
}
}
echo '<pre>';
print_r($new_array);
echo '</pre>';
Should yield something like this:
Array
(
[1] => Array
(
[111] => 36265
[444] => 36265
)
[2] => Array
(
[222] => 36265
[555] => 36265
)
)

Merging arrays within an array, preserving numeric index

Array_merge and array_merge_recursive are not working as desired, creating more indexes instead of pushing the arrays together and retaining the index number. See below for input/desired output:
Array (
[0] => array(
[0] => "string1",
[1] => "string2",
[2] => "string3"
),
[1] => array(
[0] => "string4",
[1] => "string5",
[2] => "string6"
),
[2] => array(
[0] => "string7",
[1] => "string8",
[2] => "string9"
)
)
Desired Output:
Array (
[0] => array("string1","string4","string7"),
[1] => array("string2","string5","string8"),
[2] => array("string3","string6","string9")
)
EDIT:
Perhaps not the best example; I want to achieve the same results but with an unequal number of keys in each nested array. See below for a better example:
<?php
$array = Array (
[0] => array(
[0] => "string1",
[1] => "string2",
[2] => "string3"
),
[1] => array(
[0] => "string4",
[1] => "string5",
[2] => "string6"
),
[2] => array(
[0] => "string7",
[1] => "string8",
[2] => "string9"
),
[3] => array(
[0] => "string10",
[1] => "string11",
[2] => "string12"
)
);
$output=array();
for($0=0;$j<count($array[0]);$j++){
$output[$j] = array();
}
for($i=0;$i<count($array);$i++){
for($0=0;$j<count($array[0]);$j++){
$output[$j] = array_push($output[$j],$column_values[$i][$j]);
}
}
?>
But when I do this, I get the correct number of keys in my $output array, but they all contain a bool(false). Any help?
This is the desired output:
Array (
[0] => array("string1","string4","string7","string10"),
[1] => array("string2","string5","string8","string11"),
[2] => array("string3","string6","string9","string12")
)
This is to make an array just for this structure of array, so you may change the code depanding on your needs ...
<pre>
<?php
$array = array(array("string1","string2","string3"),array("string4","string5","string6"),array("string7","string8","string9"));
$output=array();
for($i=0;$i<count($array[0]);$i++){
for($j=0;$j<count($array[0]);$j++){
$output[$i][$j] = $array[$j][$i];
}
}
print_r($output);
?>
</pre>
This is for your 'second' situation:
<?php
$array = array(array("string1","string2","string3"),array("string4","string5","string6"),array("string7","string8","string9"),array("string10","string11","string12"));
$output=array();
for($i=0;$i<count($array[0]);$i++){
for($j=0;$j<=count($array[0]);$j++){
$output[$i][$j] = $array[$j][$i];
}
}
print_r($output);
?>
Got it. Last loop should simply array_push($output[$j],$column_values[$i][$j]); instead of trying to set the variable $output[$j] = array_push(Yadda,yadda).

How can I flip an array when each value is also an array?

How would I go about flipping an array and establishing relationships between all the values and keys? For example:
I am trying to turn this:
Array (
[11913] => Array (
[0] => 4242
[1] => 3981
)
[9878] => Array (
[0] => 2901
[1] => 3981
)
[11506] => Array (
[0] => 3981
[1] => 2901
)
)
Into this:
Array (
[3981] => Array (
[0] => 11506
[1] => 9878
[2] => 11913
)
[2901] => Array (
[0] => 11506
[1] => 9878
)
[4242] => Array (
[0] => 11913
)
)
Are there any PHP functions that will already do this automatically? If not what would be a way of going about this? Can't seem to wrap my head around it.
Here you go.
$final_array = array();
foreach($initial_array as $key => $val){
foreach($val as $v){
$final_array[$v][] = $key;
}
}

Categories