PHP - Array Merge - Removing Array Keys from an Array before Merging - php

Below is the print_r($result) result of an $result = array_merge(array($id => $value), array($user => $value), array("Information" => $value)) variable in a piece of PHP code:
Array ( [id] => 1 [user] => 1
[Information] => Array ( [0] => Array ( [name] => 'John' )
[1] => Array ( [family] => 'Goldenberg' )
[2] => Array ( [age] => '21' )))
How to remove the array keys from the "Information" => $value array in PHP to make the output like below:
Array ( [id] => 1 [user] => 1
[Information] => Array ([name] => 'John'
[family] => 'Goldenberg'
[age] => '21'))
Is there any specific function in PHP to complete this task? Thanks a lot for your help.

Your "Information" array is a multidimensional one, having some arrays as the elements, in which there are some "key-value" pairs as "data". You may use the following to reinsert the "data" in the desirable way:
<?php
$info = array( array('name'=>'John'), array('family' => 'Goldenberg'), array('age' => 21));
$out = array();
foreach($info as $arr)
foreach($arr as $key => $val)
$out[$key] = $val;
print_r($out);
?>

Related

Sequence issue with nested foreach loop php

I have two array. array one and array two. I want to merge these array into single array with key. My output result is valid but sequence is not correct.
Array one
Array
(
[0] => test-685f1e7bc357187e449479d627100102
[1] => test-685f1e7bc357187e449479d627d29390
)
Array two
Array
(
[0] => DF955298-A664-4FA7-9586-FCD4CF977777
[1] => DF955298-A664-4FA7-9586-FCD4CF988888
)
Expected Result
Array
(
[0] => Array
(
[key] => test-685f1e7bc357187e449479d627100102
[uuid] => DF955298-A664-4FA7-9586-FCD4CF977777
)
[1] => Array
(
[key] => test-685f1e7bc357187e449479d627d29390
[uuid] => DF955298-A664-4FA7-9586-FCD4CF988888
)
)
My code is for that result is mentioned below:
$record = array();
foreach ($keys_array as $key => $all_key) {
foreach ($uuid_array as $uuid_key => $all_uuid) {
$record[$key]['key'] = $all_key;
$record[$uuid_key]['uuid'] = $all_uuid;
}
}
My output sequence is not valid. Where is the problem
Array
(
[0] => Array
(
[key] => test-685f1e7bc357187e449479d627100102
[uuid] => DF955298-A664-4FA7-9586-FCD4CF977777
)
[1] => Array
(
[uuid] => test-685f1e7bc357187e449479d627d29390
[key] => DF955298-A664-4FA7-9586-FCD4CF988888
)
)
Simple solution:
$record = array();
foreach ($keys_array as $key => $all_key) {
$record[] = [
'key' => $all_key,
// get value under the same key from `$uuid_array`
'uuid' => $uuid_array[$key],
];
}

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).

Removing subarrays that share a key-value pair with another multidimensional array

I have 2 arrays as below. I want to remove data from array2 if array1 has the stu_id. final array should be like result_array.
$array1 = Array
(
[0] => Array
(
[stu_id] => 1
[name] => mr.a
)
[1] => Array
(
[stu_id] => 3
[name] => mr.b
)
)
$array2 = Array
(
[0] => Array
(
[id] => 1
[stu_id] => 1
[data] => abc
)
[1] => Array
(
[id] => 2
[stu_id] => 2
[data] => xyz
)
[3] => Array
(
[id] => 3
[stu_id] => 3
[data] => aaa
)
)
$result_array = Array
(
[0] => Array
(
[id] => 2
[stu_id] => 2
[data] => xyz
)
)
I tried array_diff, $result_array = array_diff($array2, $array1); but it's not working.
Please help me to do this.
Temporarily assign keys using array_column() with stud_id (NULL retains the full subarray data), then use array_diff_key() to filter, and array_values() to reset the keys:
Code: (Demo)
$array1=[
['stu_id'=>1,'name'=>'mr.a'],
['stu_id'=>3,'name'=>'mr.b']
];
$array2=[
['id'=>1,'stu_id'=>1,'data'=>'abc'],
['id'=>2,'stu_id'=>2,'data'=>'xyz'],
['id'=>3,'stu_id'=>3,'data'=>'aaa']
];
//var_export(array_column($array1,NULL,'stu_id'));
//var_export(array_column($array2,NULL,'stu_id'));
var_export(array_values(array_diff_key(array_column($array2,NULL,'stu_id'),array_column($array1,NULL,'stu_id'))));
Output:
array (
0 =>
array (
'id' => 2,
'stu_id' => 2,
'data' => 'xyz',
),
)
If you'd like to use a foreach loop structure, generate a filtering array of stu_id's from $array1 and write a conditional check on each iteration of $array2. This method doesn't not modify the original arrays, so they can be reused "down script".
Code:
$stu_ids=array_column($array1,'stu_id');
foreach($array2 as $row){
if(!in_array($row['stu_id'],$stu_ids)){
$result[]=$row; // auto-index the qualifying subarrays
}
}
var_export($result);
// same result as above method
foreach($array1 as $data1){
foreach($array2 as $k => $data2){
if($data2["stu_id"] == $data1["stu_id"]){
unset($array2[$k]);
break;
}
}
}
$result_array = $array2;

php multidemensional array to simple array

I need this multidimensional array converted to a simple array.
Array
(
[0] => Array
(
[id_zub] => 1
[name] => Backen
)
[1] => Array
(
[id_zub] => 2
[name] => Kochen
)
)
A simple array:
array(
[id_zub] => 1
[name] => Backen
[id_zub] => 2
[name] => Kochen
)
function array_flattern($array){
foreach($array as $key=> $value){
if(is_array($value)){
$this->array_flattern($value);
}
else{
$this->result[$key] = $value;
}
}
}
The function gives me this result:
Array
(
[id_zub] => 2
[name] => Kochen
)
your function works as intended, Your getting a "key clash" and the latter key's value is the one used. You would have yo have a suffix on the key if you wanted it in one dimension
eg
Array ( [id_zub_2] => Kochen )

Splice an array when key_value same?

My sorted array needs to be split up so that each created array has all of those associated with that value.
Array (
[NAME] => Array
(
[0] => Fooaz
[1] => bzdsfdasfz
[2] => Fooooooooo
)
[DESCRIPTION] => Array
(
[0] => Foo
[1] => Foo
[2] => Barrrr
)
)
For example, from that array I want to get two arrays. One containing:
[NAME]=>Array([0] => Fooooooooo), [DESCRIPTION]=>Array([0] => Barrrr):
The other containing the remaining elements.
What's an efficient way of doing this?
$arr = Array (
'NAME' => Array
(
0 => 'Fooaz',
1 => 'bzdsfdasfz',
2 => 'Fooooooooo'
),
'DESCRIPTION' => Array
(
0 => 'Foo',
1 => 'Foo',
2 => 'Barrrr'
)
);
$arr1 = array();
foreach ($arr as $key => $value) {
$arr1[$key][] = array_pop($arr[$key]);
}
print_r($arr);
print_r($arr1);
Use array_pop():
http://codepad.org/GeP6OEtf
<?php
$arr=array(
"NAME"=>array('a','b','c','d'),
"DESC"=>array('A','B','C','D')
);
$newarr=array();
foreach ($arr as $key=>$value) {
$newarr[$key]=array(array_pop($arr[$key]));
}
print_r($arr);
echo "\n-------------\n";
print_r($newarr);
You can use extract function.
extract($array);
this will give you two arrays automatically.
reference

Categories