How to sort multiple arrays in PHP - php

i have wrote a script to produce an array of data but now want to display in order of score. The array outputs as follows;
[display_name] => Array
(
[0] => ACT_Web_Designs
[1] => user1_design
[2] => user2_design
)
[proffesion] => Array
(
[0] => Web Developer
[1] => web developer
[2] => Web Developer
)
[score] => Array
(
[0] => 15
[1] => 6
[2] => 15
)
[img] => Array
(
[0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
[1] =>
[2] =>
)
so in a nutshell I am wanting it to be converted as follows;
[display_name] => Array
(
[0] => ACT_Web_Designs
[1] => user2_design
[2] => user1_design
)
[proffesion] => Array
(
[0] => Web Developer
[1] => web developer
[2] => Web Developer
)
[score] => Array
(
[0] => 15
[1] => 15
[2] => 6
)
[img] => Array
(
[0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
[1] =>
[2] =>
)
I have been looking at asort() but cant get anything to work. any help would be much appreciated.

This is exactly where the PHP's array_multisort comes to use. It is a case where you want to sort many arrays based on the comparison happening in just one of them.
I've modified the array score to have distinct values.
<?php
$arr = array(
'display_name' => array('ACT_Web_Designs','user1_design','user2_design'),
'proffesion' => array('Web Developer','web developer','web developer'),
'score' => array(12,6,15),
'img' => array('./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic','','')
);
var_dump($arr);
array_multisort($arr['score'], SORT_ASC, SORT_NUMERIC,
$arr['display_name'],
$arr['proffesion'],
$arr['img']
);
var_dump($arr);
?>
Here goes a working demo.

How about this simpler one
$arr = array("k"=>array("A","B","C"),"l"=>array(15,6,15),"n"=>array("k","l","n"));
array_multisort($arr["k"],SORT_NUMERIC,SORT_DESC,$arr["l"],$arr["n"]);
var_dump($arr);

Doesn't it work to just rsort the score array?
rsort($data['score'], SORT_NUMERIC);

I have managed to do this, i was just after a more efficient way;
$array = array(
'display_name' => array(0 => 'ACT_Web_Designs', 1 => 'user1_design', 2 => 'user2_design' ),
'proffesion' => array( 0 => 'Web Developer', 1 => 'web developer', 2 => 'Web Developer' ),
'score' => array( 0 => 15, 1 => 6, 2 => 15 ),
'img' => array( 0 => './?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic', 1 => '', 2 => '' )
);
arsort($array['score'], SORT_NUMERIC );
foreach($array['score'] as $key => $val ) {
$newarray['display_name'][] = $array['display_name'][$key];
$newarray['proffesion'][] = $array['proffesion'][$key];
$newarray['score'][] = $array['score'][$key];
$newarray['img'][] = $array['img'][$key];
}
print_r($newarray);
returns
Array
(
[display_name] => Array
(
[0] => ACT_Web_Designs
[1] => user2_design
[2] => user1_design
)
[proffesion] => Array
(
[0] => Web Developer
[1] => Web Developer
[2] => web developer
)
[score] => Array
(
[0] => 15
[1] => 15
[2] => 6
)
[img] => Array
(
[0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
[1] =>
[2] =>
)
)

Use rsort()
<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
reset($fruits);
while (list($key, $val) = each($fruits)) {
echo "$key = $val\n";
}
?>
This example would display:
0 = orange
1 = lemon
2 = banana
3 = apple

The most elegant solution that I could find would not reorder the data structure but merely access it in a different fashion.
$scores = $data['score'];
arsort($scores);
$keys_ordered_by_score = array_keys($scores);
Now you can, say, grab the display_name and "proffesion" that has the highest score by the following:
$first_place = $keys_ordered_by_score[0];
echo $data['display_name'][$first_place],
' is a ', $data['proffesion'][$first_place];
Of course, if you really need to reorder the data structure, this idea is useless to you. Any of the other answers using array_multisort() will likely suit that need.

This will not re-sort them for you, but it will let you go through them in the order you want. You can reassign them if you want, but I'd just use this for the output order.
Edit: This will not work, due to the possibility of non-unique key values. See Comments below, and learn from my mistake
$sort_order = $array['score'];
arsort($sort_order);
$sort_order = array_flip($sort_order);
foreach($sort_order as $key){
echo $array['display_name'][$key].' - '.$array['score'][$key];
}

Related

Move an element to first position in an array

here is my array:
Array
(
[0] => Array
(
[id] => 8
[title] => MUSIC
)
[1] => Array
(
[id] => 17
[title] => Indie
)
[2] => Array
(
[id] => 14
[title] => SPORTS
)
[3] => Array // Need to move this on first position
(
[id] => 15
[title] => Hipster
)
[4] => Array
(
[id] => 16
[title] => Web Seriesdf
)
)
I want array with key [3] to be on first position and then the rest of the elements.
I tried array_merge and array_unshift. But not working
You just need to take only three steps.
- Copy n'th array in variable.
- Delete n'th index from array. using unset()
- Put variable at the 0th index of the array. Using array_unshift()
Step 1:
$array=$mainArray[N];
Step 2:
unset($mainArray[N]);
Step 3:
array_unshift($mainArray, $array);
Lets assume your array to be $x;
$new_value = $x[3];
unset($x[3]);
array_unshift($x,$new_value);
This shall solve your problem.
You can also use array_merge
<?php
$a = [1,2,3,4,5];
$new_value = [$a[1]];
unset($a[1]);
$c = array_merge($new_value,$a);
print_r($c);
?>
Check output : https://eval.in/590702
Use
$array = array('3' => $array['3']) + $array;
phpfiddle Preview and eval.in Preview
Note: im moving 2 in my array. In your method add 3
Example
$array = array(
'0' => array(
'id'=>'8',
'title'=>'MUSIC'
),
'1' => array(
'id'=> '17',
'title'=> 'Indie'
),
'2' => array(
'id'=>'14',
'title'=>'SPORTS',
),
'3' => array(
'id'=>'14',
'title'=>'SPORTS',
),
);
$array = array('2' => $array['2']) + $array;
print_r($array);
Output
Array ( [2] => Array ( [id] => 14 [title] => SPORTS ) [0] => Array ( [id] => 8 [title] => MUSIC ) [1] => Array ( [id] => 17 [title] => Indie ) [3] => Array ( [id] => 14 [title] => SPORTS ) )
Use array_unshift();
Please check below code.
<?php
$a = Array(
'0' => Array('id' => '8','title' => 'MUSIC'),
'1' => Array('id' => '17','title' => 'Indie'),
'2' => Array('id' => '14','title' => 'SPORTS'),
'3' => Array('id' => '15','title' => 'Hipster'),
'4' => Array('id' => '16','title' => 'Web Seriesdf')
);
echo '<pre>';print_r($a);
$a3 = $a['3'];
unset($a['3']);
array_unshift($a,$a3);
echo '<pre>';print_r($a);
?>
Check output - https://eval.in/590723

add items to multidimensional array programmatically in php

I have the following array
$a = array(0 => 'Item',
1 => 'Wattles',
2 => 'Types',
3 => 'Compost',
4=> 'Estimated',
5 => '123',
6 => 'Actual',
7 => '12',
);
That is sorted with the following code.
echo "<pre>";
print_r($a);
$a_len = count($a);
$fnl = array();
$i = 0;
while($i<$a_len){
$fnl[$a[$i]] = $a[++$i];
$i++;
}
print_r($fnl);
It prints correctly
Array
(
[Item] => Wattles
[Types] => Compost
[Estimated Qty] => 123
[Actual Qty] => 12
)
until i add multiple entries.
Array
(
[0] => Item
[1] => Wattles
[2] => Types
[3] => Compost
[4] => Estimated Qty
[5] => 123
[6] => Actual Qty
[7] => 12
[8] => Item
[9] => Silt Fence
[10] => Types
[11] => Straw
[12] => Estimated Qty
[13] => 45
[14] => Actual Qty
[15] => 142
)
I need to make this add items in a multidimensional array.
$items = array
(
array("Wattles","Silt Fence), //items
array("Compost","Straw"), //types
array(123,45), //estimated quantity
array(12,142) //actual quantity
);
There are a few given numbers. There are exactly 4 entries (8 items) before the list repeats itself.
I have been stuck on this portion for hours, and don't know how to get my code working as I want it to.
To get the expected result with string keys you can do:
foreach(array_chunk($a, 2) as $pairs) {
$result[$pairs[0]][] = $pairs[1];
}
Yields:
Array
(
[Item] => Array
(
[0] => Wattles
[1] => Silt Fence
)
[Types] => Array
(
[0] => Compost
[1] => Straw
)
[Estimated] => Array
(
[0] => 123
[1] => 45
)
[Actual] => Array
(
[0] => 12
[1] => 142
)
)
Then if you want it numerically indexed:
$result = array_values($result);
You have your structure for a multidimensional array wrong. You should construct your array like this:
$a = array(
0 => array(
'Item' => 'Wattles',
'Types' => 'Compost',
'Estimated' => 123,
'Actual' => 12
)
);
Then to add to it:
$a[] = array(
'Item' => 'Silt Fence',
'Types' => 'Straw',
'Estimated' => 45,
'Actual' => 142
);
Render it out to see the results which are what I think you are looking for.
print_r($a);
I can post a link if you want to learn how to sort multidimensional arrays by sub-array values if you need.

Sort array by Name in PHP

I've got an array as follows:
Array (
[id] => Array
(
[0] => 3321
[1] => 3318
[2] => 3320
[3] => 3319
[4] => 3324
[5] => 3322
)
[name] => Array
(
[0] => Carla Taku
[1] => Honey-Pearl Te Moni
[2] => Monique Koroua
[3] => Summer Hellier
[4] => Wayne Kahukiwa
[5] => Natasha Merito
)
[courses] => Array
(
[0] => 2
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
)
)
I want to sort this by "name", but I can't work out how to do this. I can't make it multi-dimensional due to some other code. I've tried usort, ksort, array_sort, array_multisort, but I'm not experienced enough to sort this.
I think array_multisort is what you are after:
array_multisort($array['name'], $array['id'], $array['courses']);
I just came across sorting stuff yesterday. Hopefully this could give you some hint.
function SortByName($a,$b){
return strcasecmp($a['name'], $b['name']);
}
usort($YourArray, 'SortByName');
Sorry for not using your specific array, I got lazy. However this should work for you, easy as pie.
$ar = array(
array("10", 11, 100, 100, "a"),
array(1, 2, "2", 3, 1)
);
$temp = $ar[1];
$count = 0;
asort($ar[0]);
foreach ($ar[0] as $key => $value) {
$ar[1][$count] = $temp[$key];
$count++;
}
print_r($ar);

Merging two array elements into one array element in PHP

I want to merge two arrays into one array as follows,
Array1:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
)
)
Array2:
Array
(
[0] => Array
(
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
Expected array result is:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
How to merge these array elements into one array element ?
foreach ($origArray as $key => &$subArray)
$subArray += $arrayToBeAdded[$key];
Where $origArray is your array which is to be merged into and $arrayToBeAdded the array you merge into.
User array_merge_recursive():
$final = array_merge_recursive($array1, $array2);
Try this little known overload of the + operator for arrays:
$result = $array1[0] + $array2[0]
Use function array_merge($array1[0], $array2[0]) . Following is the example for the same
$array1 = array(0=>array('1'=>1,'2'=>2,'3'=>3));
$array2 = array(0=>array('4'=>4,'5'=>5,'6'=>6));
$result[0] = array_merge($array1[0],$array2[0]);
echo '<pre>';
print_r($result);
Since you have unique keys, you could use something as simple as the + operator (union)...
For example:
$arr1 = [1=>'testing',2=>'stack',3=>'overflow'];
$arr2 = [4=>'something',5=>'else',6=>'here'];
$arr3 = $arr1 + $arr2;
print_r($arr3);
Results:
Array ( [1] => testing [2] => stack [3] => overflow [4] => something [5] => else [6] => here )
For this php has multiple functions. You can use $arrays = array_combine($array1, $array2);.
PHP.net - array_combine
Hope it helped!

Merging arrays within an array, preserving numeric index

Array_merge and array_merge_recursive are not working as desired, creating more indexes instead of pushing the arrays together and retaining the index number. See below for input/desired output:
Array (
[0] => array(
[0] => "string1",
[1] => "string2",
[2] => "string3"
),
[1] => array(
[0] => "string4",
[1] => "string5",
[2] => "string6"
),
[2] => array(
[0] => "string7",
[1] => "string8",
[2] => "string9"
)
)
Desired Output:
Array (
[0] => array("string1","string4","string7"),
[1] => array("string2","string5","string8"),
[2] => array("string3","string6","string9")
)
EDIT:
Perhaps not the best example; I want to achieve the same results but with an unequal number of keys in each nested array. See below for a better example:
<?php
$array = Array (
[0] => array(
[0] => "string1",
[1] => "string2",
[2] => "string3"
),
[1] => array(
[0] => "string4",
[1] => "string5",
[2] => "string6"
),
[2] => array(
[0] => "string7",
[1] => "string8",
[2] => "string9"
),
[3] => array(
[0] => "string10",
[1] => "string11",
[2] => "string12"
)
);
$output=array();
for($0=0;$j<count($array[0]);$j++){
$output[$j] = array();
}
for($i=0;$i<count($array);$i++){
for($0=0;$j<count($array[0]);$j++){
$output[$j] = array_push($output[$j],$column_values[$i][$j]);
}
}
?>
But when I do this, I get the correct number of keys in my $output array, but they all contain a bool(false). Any help?
This is the desired output:
Array (
[0] => array("string1","string4","string7","string10"),
[1] => array("string2","string5","string8","string11"),
[2] => array("string3","string6","string9","string12")
)
This is to make an array just for this structure of array, so you may change the code depanding on your needs ...
<pre>
<?php
$array = array(array("string1","string2","string3"),array("string4","string5","string6"),array("string7","string8","string9"));
$output=array();
for($i=0;$i<count($array[0]);$i++){
for($j=0;$j<count($array[0]);$j++){
$output[$i][$j] = $array[$j][$i];
}
}
print_r($output);
?>
</pre>
This is for your 'second' situation:
<?php
$array = array(array("string1","string2","string3"),array("string4","string5","string6"),array("string7","string8","string9"),array("string10","string11","string12"));
$output=array();
for($i=0;$i<count($array[0]);$i++){
for($j=0;$j<=count($array[0]);$j++){
$output[$i][$j] = $array[$j][$i];
}
}
print_r($output);
?>
Got it. Last loop should simply array_push($output[$j],$column_values[$i][$j]); instead of trying to set the variable $output[$j] = array_push(Yadda,yadda).

Categories