Remove the top level array and merge sub array into one - php

I have a multidimensional array and I want to remove the top level array and merge all its sub array into one array.
Below is my array:
$arr = [KEY1] => Array
(
[0] => Array
(
[Feb] => 120
)
[1] => Array
(
[Jan] => 230
)
[3] => Array
(
[Mar] => 340
)
)
[KEY2] => Array
(
[0] => Array
(
[Feb] => 12
)
[1] => Array
(
[Jan] => 23
)
[3] => Array
(
[Mar] => 34
)
)
I need to arrange and sort this array like below:
Output:
[KEY1] => Array
(
[Jan] => 230,
[Feb] => 120,
[Mar] => 340
)
[KEY2] => Array
(
[Jan] => 23,
[Feb] => 12,
[Mar] => 34
)
I have used
call_user_func_array('array_merge', $arr ); but not working.
Please suggest any wise way to do this.
Thanks

You can try like this as simple way,
$arr = [
'key1' =>[
0 => ["feb" => 123],
1 => ["dev" => 213],
2 => ["jan" => 111],
],
'key2' =>[
0 => ["feb" => 132],
1 => ["dev" => 321],
2 => ["jan" => 555],
],
];
$result = [];
foreach($arr as $k => $v){
foreach($v as $k1 => $v1){
foreach($v1 as $k2 => $v2)
$result[$k][$k2] = $v2;
}
}
print_r($result);
Hope this will solve your problem.
EDIT
Here is your sorting function.
function sortNestedArray(&$a)
{
sort($a);
for ($i = 0; $i < count($a); $i++) {
if (is_array($a[$i])) {
sortNestedArray($a[$i]);
}
}
return $a;
}
$a = sortNestedArray($result);
print_r($a);

Related

merge 2 array with different number of keys

I have 2 arrays
$arr1 = Array
(
[REG1] => 94
[REG3] => 45
)
$arr2 =Array
(
[0] => REG1
[1] => REG2
[2] => REG3
[3] => REG4
)
I have to loop 2 arrays and I would like a result in one array like this:
Array(
[0] => Array(
[REG1] => 94
)
[1] => Array(
[REG2] =>
)
[2] => Array(
[REG3] => 45
)
[3] => Array(
[REG4] =>
)
)
But for the instand I can not do what I want, here is where I am:
private function mergeData($arr1, $arr2){
$result = array_map(function($v1, $v2){
$t[$v1] = $v2;
return $t;
}, $arr2, $arr1);
return $result;
}
output:
Array(
[0] => Array(
[REG1] => 94
)
[1] => Array(
[REG2] =>45
)
[2] => Array(
[REG3] =>
)
[3] => Array(
[REG4] =>
)
)
I cannot correctly put the bone values with the right keys.
I tried with array_merge_recursive but also failed.
Thanks for your help
$arr3 = array_fill_keys( $arr2, '' );
creates an array containing the values of $arr2 as keys with as value an empty string.
$arr3 =Array
(
[REG1] => ''
[REG2] => ''
[REG3] => ''
[REG4] => ''
)
After that just merge.
$result = array_merge ( $arr3, $arr1 );
Another option would be to use the array_map function and map key with the corresponding values, if any:
$arr1 = [
'REG1' => 94,
'REG3' => 45
];
$arr2 = [
'REG1',
'REG2',
'REG3',
'REG4'
];
$result = array_map(function($item) use($arr1){
return [$item => isset($arr1[$item]) ? $arr1[$item] : ""];
},$arr2);
This will return:
Array
(
[0] => Array
(
[REG1] => 94
)
[1] => Array
(
[REG2] =>
)
[2] => Array
(
[REG3] => 45
)
[3] => Array
(
[REG4] =>
)
)
Using a loop:
<?php
$arr1 = [
'REG1' => 94,
'REG3' => 45
];
$arr2 = [
'REG1',
'REG2',
'REG3',
'REG4'
];
$result = $arr2;
foreach($result as &$v)
$v = [$v => $arr1[$v] ?? null];
unset($v);
var_export($result);
Output:
array (
0 =>
array (
'REG1' => 94,
),
1 =>
array (
'REG2' => NULL,
),
2 =>
array (
'REG3' => 45,
),
3 =>
array (
'REG4' => NULL,
),
)

how to convert associative array to different array?

how to convert associative array to different array?
This is my array
$array=Array (
services => Array ( [0] => 6, [1] => 1, [2] => 3 ),
subservices => Array ( [0] => 'No data',[1] => 2 ,[2] => 'No data' ),
price=> Array ( [0] => 124, [1] => 789, [2] => 895 ),
);
and i want convert to
Array (
[0] => Array ( [services] => 6, [subservices] => 'No data', [price] => 124 )
[1] => Array ( [services] => 1, [subservices] => 2, [price] => 789 )
[2] => Array ( [services] => 3, [subservices] => 'No data', [price] => 895 )
)
How to do?
$outArray=array();
for($i=0;$i<count($sourceArray['services']);$i++)
{
$outArray[]=array('services'=>$sourceArray['services'][$i],'subservices'=>$sourceArray['subservices'][$i],'price'=>$sourceArray['price'][$i]);
}
Here is a dynamic approach. This will also allow for additional values in your sub arrays.
Hope it helps:
$array = array (
'services' => Array ( '0' => 6, '1' => 1, '2' => 3),
'subservices' => Array ( '0' => 'No data', '1' => 2, '2' => 'No data'),
'price' => Array ( '0' => 124, '1' => 789, '2' => 895)
);
//Get array keys.
$keys = array_keys($array);
//Iterate through the array.
for($i = 0; $i < count($array); $i++){
//Iterate through each subarray.
for($j = 0; $j < count($array[$keys[$i]]); $j++){
//Here we are checking to see if you have more data per element than your initial key count.
if($keys[$j]){
$index = $keys[$j];
} else {
$index = $j;
}
//Append results to the output array.
$results[$i][$index] = $array[$keys[$i]][$j];
}
}
echo '<pre>';
print_r($results);
echo '</pre>';
This will output:
Array
(
[0] => Array
(
[services] => 6
[subservices] => 1
[price] => 3
)
[1] => Array
(
[services] => No data
[subservices] => 2
[price] => No data
)
[2] => Array
(
[services] => 124
[subservices] => 789
[price] => 895
)
)

PHP - Sort Array By SubArray Value By Maintaining original Array key

I would like to Sort an Array with its sub array value ("Name") but keeping its original array key.
default Array:
Array (
[251] => Array
(
[color] =>
[name] => 8
[nbr] => 1
[url_name] => taille-8
[meta_title] =>
)
[323] => Array
(
[color] =>
[name] => 7
[nbr] => 2
[url_name] => taille-7
[meta_title] =>
)
[127] => Array
(
[color] =>
[name] => 34
[nbr] => 2
[url_name] => taille-34
[meta_title] =>
)
);
By using array_multisort, I can able to get following Array:
Array(
[0] => Array
(
[color] =>
[name] => 7
[nbr] => 2
[url_name] => taille-7
[meta_title] =>
)
[1] => Array
(
[color] =>
[name] => 8
[nbr] => 1
[url_name] => taille-8
[meta_title] =>
)
[2] => Array
(
[color] =>
[name] => 34
[nbr] => 2
[url_name] => taille-34
[meta_title] =>
)
);
But what i need is,
Array(
[323] => Array
(
[color] =>
[name] => 7
[nbr] => 2
[url_name] => taille-7
[meta_title] =>
)
[251] => Array
(
[color] =>
[name] => 8
[nbr] => 1
[url_name] => taille-8
[meta_title] =>
)
[127] => Array
(
[color] =>
[name] => 34
[nbr] => 2
[url_name] => taille-34
[meta_title] =>
)
);
Thanks in adv :)
I would go with uasort, it looks much simpler to me:
// $arr is your Array
uasort($arr, function ($a, $b) {
return $a['name'] - $b['name'];
});
Here is an example: http://sandbox.onlinephpfunctions.com/code/a9f2d1e9702834b3a35206125429739222770301
$arr being your array:
//obtain list of values to sort by
foreach ($arr as $id => $value) {
$names[$id] = $value['name'];
}
$keys = array_keys($arr);
array_multisort(
$names, SORT_ASC, SORT_NUMERIC, $arr, $keys
);
$result = array_combine($keys, $arr);
You were probably missing the last step combining the array with given keys.
$arr assuming your array containing numeric keys and sort it by using array_multisort.
array_multisort will return sorted array.
array_combine will combine your original keys with sorted array.
Use:
$result = array_sort_by_column_preserve_keys($arr);
echo '<pre>';print_r($result);echo '</pre>';
Method :
function array_sort_by_column_preserve_keys($arr) {
$ar2 = [];
foreach($arr as $key => $sub) {
$ar2[ $key ] = $sub;
}
$keys = array_keys($arr);
array_multisort($ar2, SORT_ASC, SORT_NUMERIC, $arr, $keys);
return $result = array_combine($keys, $arr);
}
Please try this,
$array=array(
"251" => array(
"color" => "",
"name" => 8,
"nbr" => 1,
"url_name" => "taille-8",
"meta_title" => ""),
"323" => array(
"color" => "",
"name" => 7,
"nbr" => 2,
"url_name" => "taille-7",
"meta_title" => ""),
"127" => array(
"color" => "",
"name" => 34,
"nbr" => 2,
"url_name" => "taille-34",
"meta_title" => ""),
);
function swapArray( &$arr,$firstPos,$secondPos){
//echo PHP_EOL."swap: ".$firstPos.", ".$secondPos.PHP_EOL;
foreach($arr[$firstPos] as $k=>$v){
//echo PHP_EOL.$k." => ".$v.PHP_EOL;
$tmp=$v;
$arr[$firstPos][$k]=$arr[$secondPos][$k];
$arr[$secondPos][$k]=$tmp;
}
}
var_dump($array);
$keys=array(); // store all key values
$num=count($array);
foreach($array as $key=>$tmpArray)
$keys[]=$key;
//var_dump($keys);
for($i=0; $i<$num; $i++){
for($j=$i+1; $j<$num; $j++){
if($array[$keys[$i]]["name"]>$array[$keys[$j]]["name"]){
swapArray($array,$keys[$i],$keys[$j]);
}
}
}
var_dump($array);

Removing items from an array based on items in another array

I have 2 arrays:
Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 10 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 17:32:26 ) [1] => Array ( [intTrackId] => 1 [intAverageRating] => 7 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 18:54:35 ))
Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 5.5000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ) [1] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ))
I want to remove the items in the second which have a matching track ID in the first. So in this example, I would get:
Array ( [0] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ))
Is this possible with array_filter or is this a little complex for that?
Just use array_udiff() - it's intended to do this:
$one = Array (
0 => Array ('intTrackId' => 41, 'intAverageRating' => 10, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 17:32:26' ),
1 => Array ('intTrackId' => 1, 'intAverageRating' => 7, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 18:54:35' )
);
$two = Array (
0 => Array ('intTrackId' => 41, 'intAverageRating' => 5.5000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' ),
1 => Array ('intTrackId' => 361, 'intAverageRating' => 8.0000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' )
);
$result = array_udiff($two, $one, function($x, $y)
{
return $x['intTrackId']-$y['intTrackId'];
});
Yes it can be done with array_filter:
$array1 = array(...);
$array2 = array(...);
$newArray = array_filter($array2, function($item) use ($array1){
foreach($array1 as $elem){
if($item['intTrackId'] == $elem['intTrackId']){
return false;
}
}
return true;
});
I would first create a loop and store all track IDs from the first array in a separate array.
Then I'd loop over the second array and delete those keys that exist in the track ID array.
$track_ids = array();
foreach($array1 as $index => $items) {
$track_ids[$items['intTrackId']] = $index;
}
foreach($array2 as $items) {
if (isset($track_ids[$items['intTrackId']])) {
unset($array2[$track_ids[$items['intTrackId']]]);
}
}

Multidimensional Array Find and Update The Value using PHP

I can't get suitable title for this thread (help me). I can't describe this problem so here the example of my problem.
My array :
Array ( [0] => Array ( [answer] => a [score] => 3 )
[1] => Array ([answer] => b [score] => 4 )
[2] => Array ( [answer] => h [score] => 3)
[3] => Array ( [answer] => a [score] => 4 ))
...
And I wanna get an output like this :
Array ( [0] => Array ( [answer] => a [score] => 7 )
[1] => Array ([answer] => b [score] => 4 )
[2] => Array ( [answer] => h [score] => 3))
...
You can see a change of score subkey in index key 0. This is happen because there is two value 'a' in answer subkey from index key 0 and 3. The score changed to 7 because of the sum of both (3+4). Really I don't have an idea for this, sorry for my english and thanks for help.
Feel free to comment. :)
$merged = array();
foreach ($array as $answer) {
if (isset($merged[$answer['answer']])) {
$merged[$answer['answer']]['score'] += $answer['score'];
} else {
$merged[$answer['answer']] = $answer;
}
}
var_dump($merged);
Check this answer, not using loop :
$arr = array ( array ( 'answer' => 'a', 'score' => 3 ),
array ( 'answer' => 'b', 'score' => 4 ),
array ( 'answer' => 'h', 'score' => 3),
array ( 'answer' => 'a', 'score' => 4 ));
$t = array_reduce($arr, function($result, $item) {
if(array_key_exists($item['answer'],$result)){
$result[$item['answer']] = array('answer' => $item['answer'], 'score' => $item['score']+$result[$item['answer']]['score']);
}
else{
$result[$item['answer']] = array('answer' => $item['answer'], 'score' => $item['score']);
}
return $result;
},array());
echo "<pre>";
print_r($t);
Output :
Array
(
[a] => Array
(
[answer] => a
[score] => 7
)
[b] => Array
(
[answer] => b
[score] => 4
)
[h] => Array
(
[answer] => h
[score] => 3
)
)
I though of using a temporary array:
/* Current array */
$array = array(
array("answer" => "a", "score" => 3),
array("answer" => "b", "score" => 4),
array("answer" => "h", "score" => 3),
array("answer" => "a", "score" => 4)
);
/* Using a temporary array */
$tmp_array = array();
foreach($array as $subarray){
if(array_key_exists($subarray["answer"], $tmp_array)){
$tmp_array[$subarray["answer"]] += $subarray["score"];
}else{
$tmp_array[$subarray["answer"]] = $subarray["score"];
}
}
/* Creating a new formatted array */
$new_array = array();
foreach($tmp_array as $key => $value){
$new_array[] = array("answer" => $key, "score" => $value);
}
print_r($new_array);

Categories