Sort array by Name in PHP - 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);

Related

Concatenate value elements of two or more different arrays in PHP

I originally have this array
Array
(
[0] => Amministrativo ^25^9,11,2,10,18,4,7,^17,13,^0.75^0^0.25
[1] => Logico deduttive^7^^21,^0.75^0^-0.25
[2] => Situazionali^8^^20,^0.75^0^0.375
)
Using the function explode and array_diff i can get to this
Array
(
[0] => Amministrativo
[1] => 25
[2] => 9,11,2,10,18,4,7,
[3] => 17,13,
[4] => 0.75
[5] => 0
[6] => 0.25
)
Array
(
[0] => Logico deduttive
[1] => 7
[2] =>
[3] => 21,
[4] => 0.75
[5] => 0
[6] => -0.25
)
Array
(
[0] => Situazionali
[1] => 8
[2] =>
[3] => 20,
[4] => 0.75
[5] => 0
[6] => 0.375
)
but I would like to concatenate the elements of each array to get a unique array. I think I need to use the array_map function but I don't know how. This below is the result I would like to achieve
Array (
[0] => Amministrativo Logico deduttive Situazionali
[1] => 25 7 8
[2] => 9,11,2,10,18,4,7,
[3] => 17,13,21,20,
[4] => 0.75 0.75 0.75
[5] => 0 0 0
[6] => 0.25 -0.25 0.375
)
tnks
EDIT:
I tried the code that is here and it is fine.
But now I realized that there is also the problem that the arrays can be in variable number 1, 2, 3 or more and I can't know it before, I should adapt this code
$result = array_map(function ($item1, $item2,$item3) {
return "$item1 $item2 $item3";
}, $test[0], $test[1],$test[2]);
The lines of the original array are split with explode. The result is a two-dimensional array. This is transposed (swapping rows and columns). Then the lines are reassembled with implode.
function array_transpose(array $a) {
$r = array();
foreach($a as $keyRow => $subArr) {
foreach($subArr as $keyCol => $value) $r[$keyCol][$keyRow] = $value;
}
return $r;
}
$arr = [
'Amministrativo ^25^9,11,2,10,18,4,7,^17,13,^0.75^0^0.25',
'Logico deduttive^7^^21,^0.75^0^-0.25',
'Situazionali^8^^20,^0.75^0^0.375',
];
foreach($arr as $i => $row){
$arr[$i] = explode('^',$row);
}
$arr = array_transpose($arr);
foreach($arr as $i => $row){
$arr[$i] = implode(' ',$row);
}
var_export($arr);
Demo: https://3v4l.org/IdsDh

Sort array by date

My array has an array for each field (i.e date, name, etc.). How do I sort the array by date? Should I create another array? Can I use sort or unsort here. If yes, how? Here is my array:
Array
(
[date] => Array
(
[0] => 03/11/2019
[1] => 03/19/2019
[2] => 03/15/2019
[3] => 12/15/2018
)
[name] => Array
(
[0] => Lowa
[1] => Stephanie
[2] => Allan
[3] => Joffer
)
[number] => Array
(
[0] => 178989898
[1] => 111111111
[2] => 222222222
[3] => 333333333
)
[unit] => Array
(
[0] => HR
[1] => VPP
[2] =>
[3] => OAT
)
[department] => Array
(
[0] => Chemistry
[1] => IT
[2] => Lab
[3] => Contractor
)
)
At the end, my first element will be:
03/19/2019 Stephanie 111111111 VPP IT
I think your data can be better organized:
$newArr = Array
(
[0] => Array
(
[date] => 03/11/2019
[name] => Lowa
[number] => 178989898
[unit] => HR
[department] => Chemistry
)
[1] => Array
(
[date] => 03/19/2019
[name] => Stephanie
[number] => 111111111
[unit] => VPP
[department] => IT
)
[2] => Array
(
[date] => 03/15/2019
[name] => Allan
[number] => 222222222
[unit] =>
[department] => Lab
)
[3] => Array
(
[date] => 12/15/2018
[name] => Joffer
[number] => 333333333
[unit] => OAT
[department] => Contractor
)
);
Then, you can simply sort it by:
function cmp($a, $b) {
if ($a["date"] == $b["date"]) return 0;
return ($a["date"] < $b["date"]) ? -1 : 1;
}
usort($newArr, "cmp");
Please be warned that dates in the format "Month/Day/Year" ar not alphabetically sortable.
You definitively should use a Year/Month/Day format for your dates, or write a more specific cmp() function...
UPDATE: To answer OP's question in comment: just reverse $row and 'field' order:
for ($row = 0; $row < count($date); $row++) {
$newArr[$row]['date'] = $date[$row];
$newArr[$row]['name'] = $name[$row];
...
}
First save the keys of your array - then by using array_value convert to integer keys so you can use the ... operator.
Then you can use array_filter with null function to re-organize your array. Next step will be to get the keys back using array_map and array_combine.
Last step - sort by "data" with usort
Consider the following example:
$arr = ["date" => ["3", "7", "5"], "name" => ["aa", "bb", "cc"]]; // this can have a lot more sub-array inside
$keys = array_keys($arr); // extract the keys for later use
$res = array_map(null, ...array_values($arr)); // transposed the array
$res = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, $res); // return the keys to the transposed array
usort($res, function ($a, $b) {return strcmp($a['date'], $b['date']);} ); // sort all by "date"
Reference:
array-keys, array-filter, array-map, usort, array-values
Notice #MarcoS post comment regarding the comparing dates

Combining 2 Arrays when value is matched

So I have these arrays that is fetched from 2 different database, I would like to combine them in one array when the ['item_name'] and ['name'] is matched then getting the ['id'] from the Array2
I tried doing the in_array but since it's multi dimensional, I can't get the right output I want, I tried foreach also but I can't also get the right output or maybe I'm doing it wrong, I'm running out of idea how I could do the output I wanted.
Example Array1:
Array
(
[0] => Array
(
[item_id] => 1
[item_name] => Bag
[Color] => Purple
)
[1] => Array
(
[item_id] => 2
[item_name] => Pencil
[Color] => Yellow
)
[2] => Array
(
[item_id] => 3
[item_name] => Tumbler
[Color] => Blue
)
[3] => Array
(
[item_id] => 4
[item_name] => Shirt
[Color] => Red
)
)
Example Array2:
Array
(
[0] => Array
(
[id] => 11
[name] => Bag
)
[1] => Array
(
[id] => 22
[name] => Pencil
)
[2] => Array
(
[id] => 33
[name] => Tumbler
)
[3] => Array
(
[id] => 44
[name] => Shirt
)
[4] => Array
(
[id] => 55
[name] => Paper
)
[5] => Array
(
[id] => 66
[name] => Chair
)
[6] => Array
(
[id] => 4
[name] => Notebook
)
)
So my expected output would be:
Array
(
[0] => Array
(
[id] => 11
[name] => Bag
[Color] => Purple
)
[1] => Array
(
[id] => 22
[name] => Pencil
[Color] => Yellow
)
[2] => Array
(
[id] => 33
[name] => Tumbler
[Color] => Blue
)
[3] => Array
(
[id] => 44
[name] => Shirt
[Color] => Red
)
)
You can create a map with the names and the ID from the second array and then loop to modify the first one.
Consider the following code:
$a1 = array("item_id" => 1, "item_name" => "Bag", "Color" => "Purple");
$a2 = array("item_id" => 2, "item_name" => "Pencil", "Color" => "Yellow");
$a3 = array("item_id" => 3, "item_name" => "Tumbler", "Color" => "Blue");
$b1 = array("item_id" => 11, "item_name" => "Bag");
$b2 = array("item_id" => 22, "item_name" => "Pencil");
$b3 = array("item_id" => 33, "item_name" => "Tumbler");
$arr1 = array($a1, $a2, $a3);
$arr2 = array($b1, $b2, $b3);
$map = []; // here keys are names and value are the id
foreach($arr2 as $elem)
$map[$elem["item_name"]] = $elem["item_id"];
$ans = [];
foreach ($arr1 as $elem) {
if (array_key_exists($elem["item_name"], $map)) {
$elem["item_id"] = $map[$elem["item_name"]];
$ans[] = $elem;
}
}
echo print_r($ans);
In this way you achieve complexity of O(n) instead of O(n^2) if trying nested for-loop
Try by using foreach loop.
Check if in foreach loop if any index value match with another array then create a new array with all those values.
You can use counter here to get the value of array inside loop.
Been trying to simplify my code earlier and I think I got it, thanks to anju and David Winder, if anyone interested how I did it, this is how:
index = 0;
foreach ($array1 as $val){
foreach ($array2 as $val2){
if ($val['item_id'] == $val2['id']){
$filtered[$index]['id'] = $val2['id'];
$filtered[$index]['name'] = $val2['name'];
$filtered[$index]['color'] = $val['color'];
$index++;
}
}
}

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!

How to sort multiple arrays in 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];
}

Categories