So i got one single dimensional array like:
Array
(
[0] => md5
[1] => name
[2] => description
[3] => url
)
and one multidimensional array:
Array
(
[0] => Array
(
[0] => md5#1
[1] => name1
[2] => desc1
[3] => url1
)
[1] => Array
(
[0] => md5#2
[1] => name2
[2] => desc2
[3] => url2
)
)
and I want to use values of first array as keys for subarrays of the multidimensional one, so the output should look like:
Array
(
[0] => Array
(
[md5] => md5#1
[name] => name1
[desription] => desc1
[url] => url1
)
[1] => Array
(
[md5] => md5#2
[name] => name2
[description] => desc2
[url] => url2
)
)
Alternatively(as a bit offtopic question), how can I sort the elements of multidimensional array by values of md5 if they keys of subarray are not [md5] but [0]?
Thanks in advance!
For combining values of two arrays where values of one are keys, and values of other are values, use array_combine function:
$keysArray = [];
$multiArray = [];
$result_array = [];
foreach ($multiArray as $value) {
$result_array[] = array_combine($keysArray, $value);
}
For sorting - use usort and define your custom function:
usort($result_array, function($a, $b) { return strcmp($a['md5'], $b['md5']); });
Here is the functional-style equivalent of #u_mulder's answer.
This technique merely applies the array of key names as the keys for every row in the array.
Using arrow function syntax (available since PHP7.4), allows the custom callback to access the globally scoped $keys array without needing to explicitly write use($keys) in the function declaration.
Code: (Demo)
$first = ['md5#1', 'name1', 'description1', 'url1'];
$second = ['md5#2', 'name2', 'description2', 'url2'];
$multidimArray = [$first, $second];
$keys = ['md5', 'name', 'description', 'url'];
var_export(
array_map(
fn($row) => array_combine($keys, $row),
$multidimArray
)
);
Related
I am trying two Find Difference in two array Both of array are in different Format
First Array
Array
(
[0] => Array
(
[value] => /m/b/mb01-blue-0.jpg
)
[1] => Array
(
[value] => /m/b/mb04-black-0.jpg
)
[2] => Array
(
[value] => /m/b/mb04-black-0.jpg
)
}
Second Array
Array
(
[0] => /m/b/mb01-blue-0.jpg
[1] => /m/b/mb04-green-0.jpg
[2] => /m/b/mb04-blue-0.jpg
}
I want both of Arrays is a same format to use array_diff() function in php
Get the value column of your first array through array_column(), then check the difference between that result and the second array with array_diff().
$diff = array_diff(array_column($first, 'value'), $second);
Live demo at https://3v4l.org/19tgb
You may try this:
$array_1 = array(
"0"=> array("value" => "/m/b/mb01-blue-0.jpg"),
"1"=> array("value" => "/m/b/mb04-black-0.jpg"),
"2"=> array("value" => "/m/b/mb04-black-0.jpg"),
);
$result_1 = array_column($array_1,"value");
print_r($result_1);
To get the value of column specific from the array use array_column() php -function
Here is one-liner with array_shift,
$arr = array_map("array_shift", $arr);
array_shift - Shift an element off the beginning of array
Demo
Output:-
Array
(
[0] => /m/b/mb01-blue-0.jpg
[1] => /m/b/mb04-black-0.jpg
[2] => /m/b/mb04-black-0.jpg
)
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 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,
I have an array like this:
Array
(
[0] => Array
(
[0] => Array
(
[id] => 1234
[name] => John
)
[1] => Array
(
)
)
[1] => Array
(
[0] => Array
(
[id] => 1234
[name] => John
)
[1] => Array
(
[id] => 5678
[name] => Sally
)
[2] => Array
(
[id] => 1234
[name] => Duke
)
)
My resulting array should be the following (basically merging and getting rid of duplicates and removing null values):
Array
(
[0] => Array
(
[id] => 1234
[name] => John
)
[1] => Array
(
[id] => 5678
[name] => Sally
)
[2] => Array
(
[id] => 1234
[name] => Duke
)
)
Is there an easy way to do this using PHP's array functions?
EDIT: So far I have this:
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, $value);
}
}
print_r($result);
Use array_merge to merge the arrays. Then use array_unique to remove duplicates. Finally, to remove null keys, use a loop.
foreach($array as $key=>$value)
{
if(is_null($value) || $value == '')
unset($array[$key]);
}
Documentation on these methods can be found here.
Flatten your unnecessarily depth array structure by unpacking the subarrays into a merge call.
Filter out the empty subarrays with array_filter().
Remove the duplicate subarrays with array_unique(). (SORT_REGULAR prevents "Warning: Array to string conversion")
Code: (Demo)
var_export(
array_unique(
array_filter(
array_merge(...$array)
),
SORT_REGULAR
)
);
Optionally, call array_values() on the resultant array to re-index it (remove the old keys).
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);