This question already has answers here:
Compare 2-dimensional data sets based on a specified second level value
(9 answers)
Closed last year.
i need get value from 2 arrays...
First Array:
Array ( [0] => Array ( [id] => 1 [nombre_area] => biblioteca )
[1] => Array ( [id] => 2 [nombre_area] => enfermeria )
[2] => Array ( [id] => 3 [nombre_area] => talleres y laboratorios ) )
Second Array:
Array ( [0] => Array ( [0] => 1 [1] => biblioteca )
[1] => Array ( [0] => 3 [1] => talleres y laboratorios ) )
i need get the difference:
Array ( [0] => Array ( [id] => 2 [nombre_area] => enfermeria )
How can i do that ?
You are not operating on associative arrays at top level. You have two numeric arrays containing nested arrays. One of those contains associative arrays, the other one numeric arrays. First you could bring it in a normalized form, e.g. by $normalized = array_map( function($ar) { return array_values($ar); }, $array1 ); to the numeric form.
However, then you have two structures of the same form, but array_diff() won't perform a deep inspection. It will only compare a string representation of the elements at the first level. So you won't have another choice than recursively iterate the array, e.g. with help of the function array_walk_recursive().
You can try this one:
$array1 =Array (Array ( 'id' => 1, 'nombre_area' => 'biblioteca' ),Array ( 'id' => 2, 'nombre_area' => 'enfermeria' ),Array ( 'id' => 3 ,'nombre_area' => 'talleres y laboratorios' ) );
$array2 = Array (Array (1,'biblioteca' ), Array(3,'talleres y laboratorios' ));
$IDs = array_map(function($arr2){return $arr2[0];},$array2);
$result = array();
foreach($array1 as $arr1){
if(!in_array($arr1['id'],$IDs)) $result[] = $arr1; //compare id
}
print_r($result);
Related
This question already has an answer here:
PHP Find value in a multi-dimensional array by key
(1 answer)
Closed 1 year ago.
i am having a 2-dimensional array $a like this:
Array (
[1] => Array (
[id] => 19
[name] => SomeName
),
[2] => Array (
[id] => 23
[name] => AnotherName
),
[3] => Array (
[id] => 45
[name] => OneMoreName
)
)
And the second array $b like this:
Array (
[0] => 45
[1] => 23
[2] => 19
)
The values of 2nd array are id's from first array. The order of elements is right in 2nd array, but is not right in 1st. So, i want to re-order elements in 1st array to have finally:
Array (
[1] => Array (
[id] => 45
[name] => OneMoreName
),
[2] => Array (
[id] => 23
[name] => AnotherName
),
[3] => Array (
[id] => 19
[name] => SomeName
)
)
Of course, the number of elements can be more than 3, but in both arrays it is always the same. What standart php function or what approach can i use to do this?
You could use some array_walk function, but to be more understandable, i would use a specific algorithm:
$array1 = [
['id' => 19, 'name' => 'name19'],
['id' => 23, 'name' => 'name23'],
['id' => 45, 'name' => 'name45'],
];
$array2 = [45, 23, 19];
$newArray1 = [];
foreach ($array1 as $data){
// Get the array key from array2 with strict comparison value
$newKey = array_search($data['id'], $array2, true);
// Set it in a new array temporary
$newArray1[$newKey] = $data;
}
$array1 = $newArray1;
This way is quite short and easily understandable by someone else
One simple way:
$result = array_merge(array_flip($b), array_column($a, null, 'id'));
Index $a on the id and flip $b to get the values as the index
Merge the existing array into the ordered one, which will replace in the proper order
If you need to re-index then use array_values:
$result = array_values(array_merge(array_flip($b), array_column($a, null, 'id')));
I didn't test it but you could probably use array_intersect_key instead of array_merge.
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;
how can I compare these two arrays?
I want the result be elements that are not available in one array. For example:
Array #1
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 2
)
[2] => Array
(
[0] => c
[1] => 3
)
)
Array #2
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 2
)
)
Result
Array
(
[0] => Array
(
[0] => c
[1] => 3
)
)
In set theory this is call symmetrical difference.
First you need to remove any possible duplicates, then get the individual differences for both arrays and the merge those two individual differences.
$a = array('John', 'Bob', 'Mary', 'Serena');
$b = array('Jim', 'Mary', 'John', 'Bob');
// Remove any duplicates
$a = array_unique($a);
$b = array_unique($b);
// Get the individual differences, using array_diff()
$a_minus_b = array_diff($a, $b);
$b_minus_a = array_diff($b, $a);
// Simply merge them together to get the symmetric difference
$symmetric_difference = array_merge($a_minus_b, $b_minus_a); // produces ['Serena', 'Jim']
You may need to make the necessary changes for a 2D array if you need to.
I hope this help.
Hi I have below multidimensional arrays -
Array
(
[user_attempts] => 0
[2] => Array
(
[0] => 1
[1] => 4
)
[3] => Array
(
[0] => 32
[1] => 23
)
[4] => Array
(
[0] => asdsa
)
[1] => Array
(
[0] => Earth
)
)
and my second array is like below
Array
(
[1] => Array
(
[0] => Earth
)
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 32
[1] => 23
)
[4] => Array
(
[0] => asdsa
[1] => asdas
)
)
I need to intersect both multidimensional arrays - so the result would be
Array
(
[1] => Array
(
[0] => Earth
)
[3] => Array
(
[0] => 32
[1] => 23
)
)
Can anyone help me to sort this out.
What I have tried is using array_intersect() but it limits to single array not multidimensional i guess.
PHP comes with a ton of functions already built in, but sometimes you still have to implement things yourself. What you want to do can be easily done by using the existing functions.
The goal is to do the following steps:
Find the keys that exist in both arrays
Loop through the array using these keys
Take the items of both input arrays with each of these keys
Calculate the intersection of those two arrays
Put it into a result array
Here is one way to do this:
function array_intersect_2dim (array $a1, array $a2) {
$keys = array_intersect(array_keys($a1), array_keys($a2));
$return = array();
foreach ($keys as $key) {
$return[$key] = array_intersect($a1[$key], $a2[$key]);
if (sizeof($return[$key]) == 0) {
unset($return[$key]);
}
}
return $return;
}
It works only for two dimensions. If you need more, you have to build a recursive approach, which follows the exact same principle.
To make the easier to compare you can use serialize/unserialize on this one. And then use array_intersect(). Try this example: Sample Output
$array1 = array( 'user_attemps' => 0, 2 => array(1, 4), 3 => array(32, 23), 4 => array('asdsa'), 1 => array('Earth'),);
$array2 = array( 1 => array('Earth'), 2 => array(2, 3), 3 => array(32, 23), 4 => array('asdsa', 'asdas'),);
$result = array_map('unserialize',array_intersect(array_map('serialize', $array1), array_map('serialize', $array2)));
print_r($result);
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
I have this associative array below:
Array
(
[0] => Array
(
[0] => Category
[1] => fruit
[2] => carbs
)
[1] => Array
(
[0] => Day 1 - Program
[1] => Eat banana
[2] => Eat bread
)
[2] => Array
(
[0] => Day 1 - record
[1] =>
[2] =>
)
)
each array index relates to the same index in the other arrays.
I need to now create 3 arrays by combining the index. The finished array would
look like this:
Array
(
[0] => Array
(
[0] => Category
[1] => Day 1 - Program
[2] => Day 1 - record
)
[1] => Array
(
[0] => fruit
[1] => Eat banana
[2] =>
)
[2] => Array
(
[0] => carbs
[1] => bread
[2] =>
)
)
The empty slots are where I know to put a textbox to record the data.
I've tried nesting for loops and other things but nothing is working.
How to combine array into a multidimensional array based on indexes?
$output = call_user_func_array(
'array_map',
array_merge(
array(NULL),
$input
)
);
Demo
You can achieve this with a nested loop. Loop through the sub-arrays first. On each iteration, loop through the elements in the sub-array, and add them into the result array. The important part here is what we use as the index for the $result array. $index will be the position of the array element in the sub-array. For example, Category would have an index of 0, so it would be pushed to $result[0][].
foreach ($array as $sub) {
foreach ($sub as $index => $val) {
$result[$index][] = $val;
}
}
print_r($result);
Demo
Here's a quick way - it essentially flips the keys. BTW, the first array you have is an indexed array, not an associative array.
$input = array(
array
(
"Category", "fruit", "carbs"
),
array
(
"Day 1 - Program","Eat banana","Eat bread"
),
array
(
"Day 1 - record", "", ""
)
);
foreach ($input as $key => $array){
foreach ($array as $k => $v){
$output[$k][$key] = $input[$key][$k];
}
}
print_r($output);