PHP - Reorder array to match the order of another array - php

I have 1 array that has the right values that I need but it is out of order. I then have another array with the same keys and it is in the right order but the values are not what I need.
Here is my first array with the correct values but is out of order:
Array
(
[countTotal] => 7268
[zip] =>
[yearName] =>
[countZipRadius] =>
[Acura] => 1334
[Cadillac] => 511
[Ford] => 5423
)
Here is my second array with the right order but the wrong values:
Array
(
[countZipRadius] => 0
[zip] => 1
[yearName] => 2
[Acura] => 3
[Cadillac] => 4
[Ford] => 5
[countTotal] => 6
)
I am trying to figure out a way to create a new array with the right values from array 1 but that is in the order of array 2.
I have been playing with it for awhile and cannot seem to get it.
Any help would be great.
Thanks!

$c = array();
foreach (array_keys($b) as $k) {
$c[k] = $a[k];
}

You could use php's array_multisort function:
$original = array(
'countTotal' => 7268,
'zip' => '',
'yearName' => '',
'countZipRadius' => '',
'Acura' => 1334,
'Cadillac' => 511,
'Ford' => 5423,
);
$right = array(
'countZipRadius' => 0,
'zip' => 1,
'yearName' => 2,
'Acura' => 3,
'Cadilac' => 4,
'Ford' => 5,
'countTotal' => 6
);
//make sure both arrays are in the same order
ksort($original);
ksort($right);
array_multisort($right, $original);
print_r($original);
When you give it two arrays with the same number of elements it sorts both arrays, based on the order of the first array - in this case the 0, 1, 2, 3, etc. values in $right

Create a New Array (Array C)
Use a FOR loop to go through Array B
For each value in Array B, get the value with the same key from Array A and set Array C append those values to Array C. This will put them in the correct order in C.

Using scones' method:
$original = array(
'countTotal' => 7268,
'zip' => '',
'yearName' => '',
'countZipRadius' => '',
'Acura' => 1334,
'Cadillac' => 511,
'Ford' => 5423,
);
$right = array(
'countZipRadius' => 0,
'zip' => 1,
'yearName' => 2,
'Acura' => 3,
'Cadilac' => 4,
'Ford' => 5,
'countTotal' => 6
);
foreach ($right as $key => $value) {
$new[$key] = $original[$key];
}
print_r($new);

$array = array('a' => 100, 'b' => '5');
$newArray = array_combine(array_keys($array), range(0, count($array) - 1));
var_dump($newArray);

Related

Merge Array Issue

I have several arrays that all have this structure:
array (
526744 =>
array (
'completed' => 13,
'total' => 24,
'topics' =>
array (
),
'lessons' =>
array (
526745 => 1,
526747 => 1,
526749 => 1,
526751 => 0,
526757 => 0,
526759 => 0,
526761 => 1,
526763 => 0,
526765 => 0,
526767 => 1,
),
'last_id' => 526793,
),
526818 =>
array (
'completed' => 0,
'total' => 22,
'topics' =>
array (
),
'lessons' =>
array (
526819 => 0,
526821 => 1,
526823 => 1,
526845 => 0,
526847 => 1,
526849 => 1,
526859 => 1,
526861 => 1,
),
'last_id' => 526861,
),
)
The number in the outer-most element of the array is a course id. The list of numbers in the inner-most array elements are lesson ids.
I want to merge all of the arrays that contain this structure together. But only ones with the course id of 526744.
If I do something like this:
foreach($results2 as $result2) {
$new_array = unserialize($result2->course_progress);
$final_array = array_merge($final_array, $new_array);
$backup_array = $new_array;
}
This works fine, but it merges the entire arrays, including all courses.
However if I specify the course_id like this:
foreach($results2 as $result2) {
$new_array = unserialize($result2->course_progress);
$newarray = $new_array[526744];
$final_array = array_merge($final_array, $new_array);
$backup_array = $new_array;
}
It no longer merges at all and just lists out the last array for that 1 single course specified.
Any ideas on what is causing this and how to fix it?
Thanks
I have check your code and found the issue, you have used $new_array[526744] which is wrong. it should be array($new_array[526744])
Check this code:
foreach($results2 as $result2) {
$new_array = unserialize($result2->course_progress);
$newarray = array($new_array[526744]);
$final_array = array_merge($final_array, $new_array);
$backup_array = $new_array;
}

PHP SPLIT array based on key range

I've an array.
Array
(
[initial] => MSS
[hour] => 5.2
[row_checker_1] => 1
[project_name_1] => KGD001
[project_shortcode_1] => KGD001
[5_1] => 23
[6_1] => 3.3
[4_1] => 23.2
[remarks_1] => on going
[task_id] => 76
[row_checker_2] => 2
[project_name_2] => DG001
[project_shortcode_2] => DG001
[5_2] => 1.1
[6_2] => 2.2
[4_2] => 3.1
[remarks_2] => on going
)
Now I want to split all element upper range key is "project_shortcode_1" and lower range key is remarks_1.
So, new array should look like:
array
(
[5_1] => 23
[6_1] => 3.3
[4_1] => 23.2
)
Use array_filter with flag ARRAY_FILTER_USE_KEY for using the array keys, and do the comparison with the logic needed to get the desired keys. It works from PHP 5.6.
$arr = array ( "initial" => "MSS",
"hour" => 5.2,
"row_checker_1" => 1,
"project_name_1" => "KGD001",
"project_shortcode_1" => "KGD001",
"5_1" => 23,
"6_1" => 3.3,
"4_1" => 23.2,
"remarks_1" => "on going",
"task_id" => 76,
"row_checker_2" => 2,
"project_name_2" => "DG001",
"project_shortcode_2" => "DG001",
"5_2" => 1.1,
"6_2" => 2.2,
"4_2" => 3.1,
"remarks_2" => "on going",
);
// PHP > 5.6
$result = array_filter($arr, function($k){
$var = explode('_', $k);
return is_numeric($var[0]) && $var[1]==1;
}, ARRAY_FILTER_USE_KEY);
If what you need is a multidimensional array with all the ranges NUMBER_N, then use something like this (extended from Dmitriy Demir answer):
$myArray = array(
'initial' => 'MSS',
'hour' => '5.2',
'row_checker_1' => '1',
'project_name_1' => 'KGD001',
'project_shortcode_1' => 'KGD001',
'5_1' => '23',
'6_1' => '3.3',
'4_1' => '23.2',
'remarks_1' => 'on going',
'task_id' => '76',
'row_checker_2' => '2',
'project_name_2' => 'DG001',
'project_shortcode_2' => 'DG001',
'5_2' => '1.1',
'6_2' => '2.2',
'4_2' => '3.1',
'remarks_2' => 'on going'
);
function splitRange($a){
$newArray = array();
foreach ($a as $k => $v) {
$rightFormat = preg_match('/^\d+_(\d+)$/', $k, $index);
if ($rightFormat)
$newArray[$index[1]][$k] = $v;
}
return $newArray;
}
print_r(splitRange($myArray));
The result will be something like:
Array
(
[1] => Array
(
[5_1] => 23
[6_1] => 3.3
[4_1] => 23.2
)
[2] => Array
(
[5_2] => 1.1
[6_2] => 2.2
[4_2] => 3.1
)
)
being N from NUMBER_N the index of the array.
Since you mentioned in the comments that you'd prefer to get all values that are in format NUMBER_1 I think you'd need to loop through your array and check the value names with regex, then add the values to a new array if they meet the criteria. Here's how I would do this:
$myArray = array(
'initial' => 'MSS',
'hour' => '5.2',
'row_checker_1' => '1',
'project_name_1' => 'KGD001',
'project_shortcode_1' => 'KGD001',
'5_1' => '23',
'6_1' => '3.3',
'4_1' => '23.2',
'remarks_1' => 'on going',
'task_id' => '76',
'row_checker_2' => '2',
'project_name_2' => 'DG001',
'project_shortcode_2' => 'DG001',
'5_2' => '1.1',
'6_2a' => '2.2',
'4_2' => '3.1',
'remarks_2' => 'on going'
);
$newArray = array();
foreach ($myArray as $k => $v) {
$rightFormat = preg_match('/^\d+_\d+$/', $k);
if ($rightFormat)
$newArray[$k] = $v;
}
print_r($newArray);
The result of print_r in that case would be:
Array ( [5_1] => 23 [6_1] => 3.3 [4_1] => 23.2 [5_2] => 1.1 [6_2] =>
2.2 [4_2] => 3.1 )
If the number after the underscore should always be 1 then change the regex from /^\d+_\d+$/ to /^\d+_1$/.
You can play around and see how regex works here.
PS: I've set all values to strings out of convenience. Feel free to modify that.
A regex-based solution seems fitting for this question.
preg_grep() is a function designed to apply a regex filter upon each value in an array. I little more tweaking is necessary for this case because the keys must be filtered instead.
The One-liner:
$output=array_intersect_key($input,array_flip(preg_grep("/^\d+_1$/",array_keys($input)))));
/* array (
'5_1' => 23,
'6_1' => 3.3,
'4_1' => 23.2,
)*/
Here is the step-by-step array manipulation...
array_keys($input); // create array with input keys as values
/* array (
0 => 'initial',
1 => 'hour',
2 => 'row_checker_1',
3 => 'project_name_1',
4 => 'project_shortcode_1',
5 => '5_1',
6 => '6_1',
7 => '4_1',
8 => 'remarks_1',
9 => 'task_id',
10 => 'row_checker_2',
11 => 'project_name_2',
12 => 'project_shortcode_2',
13 => '5_2',
14 => '6_2',
15 => '4_2',
16 => 'remarks_2',
) */
preg_grep("/^\d+_1$/",array_keys($input)); // filter the input array using regex pattern
/* array (
5 => '5_1',
6 => '6_1',
7 => '4_1',
) */
array_flip(preg_grep("/^\d+_1$/",array_keys($input))); // flip the filtered array
/* array (
'5_1' => 5,
'6_1' => 6,
'4_1' => 7,
)*/
array_intersect_key($input,array_flip(preg_grep("/^\d+_1$/",array_keys($input)))); // filter input by comparing keys against filtered array
/* array (
'5_1' => 23,
'6_1' => 3.3,
'4_1' => 23.2,
)*/

Appending multiple values to associative array in PHP [duplicate]

This question already has answers here:
Merge two 2d arrays by shared column value
(6 answers)
Closed last month.
I would like to create a PHP array that will end up looking like this:
idPlayer namePlayer Points
1 John 20
2 Sam 25
3 Ben 22
But I would like to append the values not all at once:
First append the idPlayer and namePlayer
Then append the points for that idPlayer (I would have a $idPlayer variable to use each time I loop)
How could I do this in PHP?
I was thinking:
$myArray['idPlayer'] = "1";
$myArray['namePlayer'] = "John";
$myArray['Points'] = "20"
And then, how would I tell the array to go to the next row?
// output array
$myArray = array();
// your loop
while (something) {
// make an array for this iteration
$itarr = array();
// put stuff in it
$itarr['idPlayer'] = "1";
$itarr['namePlayer'] = "John";
$itarr['Points'] = "20"
// append it to output array using standard array indexing
$myArray[] = $itarr;
// OR, your own index
$myArray[$itarr['idPlayer']] = $itarr;
}
I dont know why you want to achieve such thing. But consider this example:
// like player table array initial
$players = array(
array(
'idPlayer' => 1,
'namePlayer' => 'John',
),
array(
'idPlayer' => 2,
'namePlayer' => 'Sam',
),
array(
'idPlayer' => 3,
'namePlayer' => 'Ben',
),
);
// data points to be added later (like points table)
$points = array(
array(
'idPlayer' => 1,
'Points' => 20,
),
array(
'idPlayer' => 2,
'Points' => 25,
),
array(
'idPlayer' => 3,
'Points' => 22,
),
);
$myArray = array();
foreach($players as $key => $value) {
foreach($points as $index => $element) {
// if this particular id matches the record inside points table then merge
if($value['idPlayer'] == $element['idPlayer']) {
$myArray[] = array('idPlayer' => $value['idPlayer'], 'namePlayer' => $value['namePlayer'], 'Points' => $element['Points']);
}
}
}
Should output something like: (can be used in a tabular data)
Array
(
[0] => Array
(
[idPlayer] => 1
[namePlayer] => John
[Points] => 20
)
[1] => Array
(
[idPlayer] => 2
[namePlayer] => Sam
[Points] => 25
)
[2] => Array
(
[idPlayer] => 3
[namePlayer] => Ben
[Points] => 22
)
)
Use the idPlayer as index:
$players = [
1 => [
'namePlayer' => 'John',
'points' => 20,
],
5 => [
'namePlayer' => 'Seth',
'points' => 25,
],
13 => [
'namePlayer' => 'Ben',
'points' => 35,
],
];
var_dump($players);
http://codepad.viper-7.com/nSXmZF
In php <5.4 use array() instead of [] constructor.

need soting multi dimensional array based on another array displaying order

I need sorting array based another array sort value.
Actual array : array(name=>'JK',age=>'20',place=>'India',year=>array(marks1=>array(sub1=>50,sub3=>70,sub7=>65,sub5=>75,sub4=>35), marks2=>array(sub8=>50,sub10=>70,sub12=>75,sub9=>35,sub11=>65))
sorting order array : array(name=>1,year=>2,age=>3,place=>4,sub1=>5,sub3=>6,sub4=>7,sub5=>8,sub7=>9,sub8=>10,sub9=>11,sub10=>12,sub11=>13,sub12=>14)
expected result array:
array(
name=>'JK',
year=>array(
marks1=>array(
sub1=>50,
sub3=>70,
sub4=>35,
sub5=>75
sub7=>65
),
marks2=>array(
sub8=>50,
sub9=>35,
sub10=>70,
sub11=>65,
sub12=>75
),
age=>'20',
place=>'India'
)
I hope this will help :)
$array1 = array(name=>'JK',age=>'20',place=>'India',year=>array(marks1=>array(sub1=>50,sub3=>70,sub7=>65,sub5=>75,sub4=>35), marks2=>array(sub8=>50,sub10=>70,sub12=>75,sub9=>35,sub11=>65));
$array2 = array(name=>1,year=>2,age=>3,place=>4,sub1=>5,sub3=>6,sub4=>7,sub5=>8,sub7=>9,sub8=>10,sub9=>11,sub10=>12,sub11=>13,sub12=>14);
//final array
$final_array = array();
//for each value in sorting array
foreach ($array2 as $key => $value)
{
//store result in final array
$final_array[$value] = $array1[$key];
}
//display array for check result
var_dump($final_array);
I am not exactly sure what is being asked. However, I will take a shot. I think the function you are looking for is uksort.
<?php
$array1 = array(name=>'JK',age=>'20',place=>'India',year=>array(marks1=>array(sub1=>50,sub3=>70,sub7=>65,sub5=>75,sub4=>35), marks2=>array(sub8=>50,sub10=>70,sub12=>75,sub9=>35,sub11=>65)));
function sorter($a,$b)
{
$array2 = array(name=>1,year=>2,age=>3,place=>4,sub1=>5,sub3=>6,sub4=>7,sub5=>8,sub7=>9,sub8=>10,sub9=>11,sub10=>12,sub11=>13,sub12=>14);
return $array2[$a] > $array2[$b];
}
uksort($array1, "sorter");
var_dump($array1);
?>
Here is an example of it running on codepad. You will probably have to work out a bit more since the subs are not sorted. But, possibly is_array can help you out.
$arr1 = array(
'name' => 'JK',
'age' => 20,
'place' => 'India',
'year' =>
array(
'marks1' =>
array('sub1' => 50,
'sub3' => 70,
'sub7' => 65,
'sub5' => 75,
'sub4' => 35),
'marks2' =>
array('sub8' => 50,
'sub10' => 70,
'sub12' => 75,
'sub9' => 35,
'sub11' => 65)));
$arr2 = array('name' => 1, 'year' => 2, 'age' => 3, 'place' => 4, 'sub1' => 5, 'sub3' => 6, 'sub4' => 7, 'sub5' => 8, 'sub7' => 9, 'sub8' => 10, 'sub9' => 11, 'sub10' => 12, 'sub11' => 13, 'sub12' => 14);
foreach ($arr1['year'] as $key => &$value){
uksort($value, function ($a, $b) use($arr2){
return $arr2[$a] - $arr2[$b];
});
}
uksort($arr1, function ($a, $b) use($arr2){
return $arr2[$a] - $arr2[$b];
});
print_r($arr1);
Output:
Array
(
[name] => JK
[year] => Array
(
[marks1] => Array
(
[sub1] => 50
[sub3] => 70
[sub4] => 35
[sub5] => 75
[sub7] => 65
)
[marks2] => Array
(
[sub8] => 50
[sub9] => 35
[sub10] => 70
[sub11] => 65
[sub12] => 75
)
)
[age] => 20
[place] => India
)

Counting values within multidimensional arrays?

I have a large array where I basically need to count the number of uniques:
example array
The end result I am looking for something like
$result = array(
'A3D5' => array('P2' => 1, 'P3' => 1, 'P4' => 1, 'total' => 3),
'AE5S' => array('P4' => 1, 'total' => 1)
);
I've tried foreaching through but can't seem to figure out how to sort them into another key, something like $zone = "P{$array['zone']}"; $result[$zone][$prestige]++ or seems to kind of not work or just error.
$array = array(
"denizen" => array
(
"prestige" => 2,
"zone" => "A3D5",
"scope_frag" => 765
),
"생각" => array
(
"prestige" => 4,
"zone" => "A3D5",
"scope_frag" => 135
),
"Ryans" => array
(
"prestige" => 3,
"zone" => "A3D5",
"scope_frag" => 78
),
"지적인" => array
(
"prestige" => 2,
"zone" => "AE5S",
"scope_frag" => 481
)
);
foreach ($array as $group) {
$zones[$group["zone"]][] = $group["prestige"];
}
foreach ($zones as $name => $zone) {
$total = count($zone);
foreach ($zone as $prestige) {
$result[$name]["P".$prestige] += 1;
}
ksort($result[$name]);
$result[$name]["total"] = $total;
}
echo "<pre>";
print_r($result);
echo "</pre>";

Categories