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);
Related
What is the most efficient way in initializing large amount of multidimensional array in PHP?
example: I'm going to create 100 Multidimensional array that look like this:
Array
(
[1] => Array
(
[multi] => 1
)
[2] => Array
(
[multi] => 2
)
[3] => Array
(
[multi] => 3
)
[4] => Array
(
[multi] => 4
)
[5] => Array
(
[multi] => 5
)
.......
)
Currently, I'm using this code to create the array shown above:
// 100 arrays
for($i=1; $i<=100; $i++){
$array[$i]['multi']=$i;
}
I also found an alternative way by using array_fill() and array_fill_keys(), but It only allows the same value to be initialized in an array:
$array = array_fill(1, 100, array_fill_keys(array("multi"), "value_here"));
QUESTION: Is there a more efficient way in initializing this kind of array in terms of speed?
You could use array_map over the range of values you want:
$array = array_map(function ($v) { return array('multi' => $v); }, range(0, 5));
print_r($array);
Output:
Array
(
[0] => Array
(
[multi] => 0
)
[1] => Array
(
[multi] => 1
)
[2] => Array
(
[multi] => 2
)
[3] => Array
(
[multi] => 3
)
[4] => Array
(
[multi] => 4
)
[5] => Array
(
[multi] => 5
)
)
If you don't want the 0 element, just unset($array[0]);
Demo on 3v4l.org
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;
This question already has answers here:
multi dimensional array in random order
(4 answers)
Closed 6 years ago.
Is it possible to get random data from an array?
See My Array:
Array
(
[0] => Array
(
[0] => My Data
[1] => Airport
[2] => Md
)
[1] => Array
(
[0] => Live in fear
[1] => Science
[2] => Sc
)
[2] => Array
(
[0] => State History
[1] => Government
[2] => MP
)
[3] => Array
(
[0] => Real Estate
[1] => Other
[2] => Property
)
[4] => Array
(
[0] => Real State
[1] => Not Sure
[2] => NoData
)
)
I need this type of random output...
Array
(
[0] => Array
(
[0] => My Data
[1] => Airport
[2] => Md
)
[1] => Array
(
[0] => Real State
[1] => Not Sure
[2] => NoData
)
[2] => Array
(
[0] => My Data
[1] => Airport
[2] => Md
)
[3] => Array
(
[0] => State History
[1] => Government
[2] => MP
)
[4] => Array
(
[0] => Live in fear
[1] => Science
[2] => Sc
)
)
Try the following shuffle function.Hope it would help you.
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[] = $list[$key];
}
return $random;
}
$arr = array();
$arr[] = array('id' => 50, 'foo' => 'hello');
$arr[] = array('id' => 17, 'foo' => 'byebye');
$arr[] = array('id' => 19, 'foo' => 'foo');
print_r(shuffle_assoc($arr));
You could simply use shuffle()
bool shuffle ( array &$array )
This function shuffles (randomizes the order of the elements in) an array. It uses a pseudo random number generator that is not suitable for cryptographic purposes.
shuffle($array); // Shuffles your array keys randomly every time.
shuffle() will be a better option in getting out the random value from multi dimensional array.
Reference: http://php.net/manual/en/function.shuffle.php
shuffle() Example:
The shuffle() function randomizes the order of the elements in the array.
This function assigns new keys for the elements in the array. Existing keys will be removed
<?php
$my_array = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"purple");
shuffle($my_array);
print_r($my_array);
?>
Output:
Array ( [0] => red [1] => yellow [2] => green [3] => blue [4] => purple )
//The Output will keep shuffling if you refresh the browser.
I have two arrays and would like to combine / merge / put them together.
$arr1 = array(
0 => array(1, 2),
1 => array(5, 6)
);
$arr2 = array(
0 => array(2, 3),
1 => array(6, 7)
);
come_together_right_now($arr1, $arr2); // the missing function?
and the result would be:
Array (
[0] => Array (
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array (
[0] => 5
[1] => 6
[2] => 7
)
There are way too many array functions! array_merge and array_combine and the recursive alternatives seem to replace the values and they don't preserve numeric keys. How do I do this?
Assuming that they will always have the same keys!
$result = array();
foreach($arr1 as $key=>$array) {
$result[$key] = array_merge($array, $arr2[$key]);
}
I might be late of answering this question but this might help you simply using array_map,array_merge and array_unique function like as
$result = array_map('array_unique',array_map('array_merge',$arr1,$arr2));
print_r($result);
Output
Array (
[0] => Array (
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array (
[0] => 5
[1] => 6
[2] => 7
)
Demo
Synchronously iterate the arrays to access their rows.
Merge rows, remove duplicates, then re-index the elements.
Code: (Demo)
var_export(
array_map(
fn(...$rows) => array_values(array_unique(array_merge(...$rows))),
$arr1,
$arr2
)
);
This is an issue I haven't come across before, and there doesn't appear to be a function for this.
I'm trying to sort the following multi dimensional array by its keys
Array (
[hiphop] => Array (
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
[rnb] => Array (
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
[dubstep] => Array ( )
[reggae] => Array ( )
[trap] => Array ( )
)
From this arrays values
Array (
[0] => hiphop
[1] => dubstep
[2] => reggae
[3] => trap
[4] => rnb
[5] => rnb
)
Has anyone attempted this before or know a workaround?
An explanation would be great as I'm new to multi dimensional arrays
Many thanks in advance if you can help!
The final output would match the value organsiation from the non multi dimensional array like so
Array (
[hiphop] => Array (
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
[dubstep] => Array ( )
[reggae] => Array ( )
[trap] => Array ( )
[rnb] => Array (
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
)
The easiest Way would be to "flip" the array definining the sorting - then grab the values matching the new keys in the other array:
$s = array ("hiphop","dubstep","reggae","trap","rnb");
$target = array_flip($s);
foreach($target AS $key => &$value){
$value = $array_containing_unsorted_values[$key];
}
Note: does not work if the same value appears twice in the sorting array - but that never should happen, cause does not make sence for a sorting-definition.
Should be way faster than using array_search 2 times within each sorting comparission.
result:
Array
(
[hiphop] => Array
(
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
[dubstep] => Array
(
)
[reggae] => Array
(
)
[trap] => Array
(
)
[rnb] => Array
(
[0] => 2123
[1] => 5683
[2] => 2345
[3] => 4567
)
)
You can use uksort for that, which lets you sort by key, based on a user supplied comparison function. Using that function, you can make a function yourself, so you can hide the complex functionality in an easy one.
For instance, you want a function like ksort, only you want to specify an external array of keys, so such a function could look like this:
bool ksort_ext(&$array, $keys)
For the implementation, you can wrap uksort, like so:
function ksort_ext(&$array, $keys)
{
return uksort($array, function($a, $b) use ($keys) {
// Result of callback is based on the position of $a and $b in $keys
return array_search($a, $keys) - array_search($b, $keys);
});
}
Then, you can call it like you would call other sort functions, only with the external array of keys as a second parameter.
$array1 = array(
'hiphop' => array(1,2,3),
'rnb' => array(1,2,3),
'dubstep' => array(1,2,3),
'reggae' => array(1,2,3),
'trap' => array(1,2,3));
$array2 = array('hiphop', 'dubstep', 'reggae', 'trap', 'rnb');
var_dump(ksort_ext($array1, $array2)); // Should return true
var_dump($array1); // Should display the ordered array,