How to order a php array based on custom value - php

I have the following php array:
array(4) {
[0]=>
array(3) {
["POSITION"]=>
string(6) "Marketer"
["FIRSTNAME"]=>
string(7) "John1"
["EMAIL"]=>
string(13) "example1#mail.com"
}
[1]=>
array(3) {
["POSITION"]=>
string(10) "Designer"
["FIRSTNAME"]=>
string(6) "John2"
["EMAIL"]=>
string(29) "example2#mail.com"
}
[2]=>
array(3) {
["POSITION"]=>
string(7) "CEO"
["FIRSTNAME"]=>
string(6) "John3"
["EMAIL"]=>
string(21) "example3#mail.com"
}
[3]=>
array(3) {
["POSITION"]=>
string(10) "Developer"
["FIRSTNAME"]=>
string(5) "John4"
["EMAIL"]=>
string(25) "example4#mail.com"
}
}
I want to reorder it based on [POSITION] column as follows:
CEO
Marketer
Developer
Designer
How can I do this? Any help would be highly appreciated.
Thanks

Put the positions in an array, then use this in the comparison function in usort().
$positions = [
'CEO' => 1,
'Marketer' => 2,
'Developer' => 3,
'Designer' => 4
];
usort($array, function($a, $b) use ($positions) {
return $positions[$a['POSITION']] - $positions[$b['POSITION']];
})

Related

Gwt data string from inside a nested array

I have an array with a lot of nested array data.
I need to get:
array(4) { ["id"]=> int(90)
this number, the 90.
Please see the whole array data below.
Thank you very much for help.
array(2)
{ ["_sft_product_cat"]=>array(5)
{
["name"]=> string(18)
"Produkt-Kategorien"
["singular_name"]=> string(9)
"Kategorie"
["all_items_label"]=> string(15)
"Alle Kategorien"
["type"]=> string(8)
"taxonomy"
["active_terms"]=> array(1)
{ [0]=> array(4)
{ ["id"]
=> int(90) ["name"]
=> string(7) "Hyundai" ["value"]
=> string(7) "hyundai" ["count"]
=> int(0)
}
}
}
["_sft_pa_typ"]=> array(5)
{ ["name"]
=> string(18) "Produkt Typ/Modell" ["singular_name"]
=> string(10) "Typ/Modell" ["all_items_label"]
=> string(5) "Al le " ["type"]
=> string(8) "taxonomy" ["active_terms"]
=> array(1)
{ [0]=> array(4)
{ ["id"]
=> int(9040) ["name"]
=> string(8) "Coupe GK" ["value"]
=> string(8) "coupe-gk" ["count"]=> int(0) } } } }
You're looking for:
$whatever_your_var_name_is["_sft_product_cat"]["active_terms"][0]["id"]
That is the same as referencing the levels one by one...
$sft_product_cat = $whatever_your_var_name_is['_sft_product_cat'];
$active_terms = $sft_product_cat['active_terms'];
$first_terms = $active_terms[0];
$id = $first_terms['id'];
It's notable that active_terms has a numeric indexed array (the [0] part). It's a hint that other instances of '_sft_product_cat' might have more than 1 terms and you'll need a loop to get them all.
I'm not familiar with php, but firstly I would format and indent the code to get a better picture of what you need from the nested objects:
array(2) {
["_sft_product_cat"]=> array(5)
{
["name"]=> string(18) "Produkt-Kategorien"
["singular_name"]=> string(9) "Kategorie"
["all_items_label"]=> string(15) "Alle Kategorien"
["type"]=> string(8) "taxonomy"
["active_terms"]=> array(1)
{
[0]=> array(4)
{
["id"]=> int(90)
["name"]=> string(7) "Hyundai"
["value"]=> string(7) "hyundai"
["count"]=> int(0)
}
}
}
["_sft_pa_typ"]=> array(5)
{
["name"]=> string(18) "Produkt Typ/Modell"
["singular_name"]=> string(10) "Typ/Modell"
["all_items_label"]=> string(5) "Alle "
["type"]=> string(8) "taxonomy"
["active_terms"]=> array(1)
{
[0]=> array(4)
{
["id"]=> int(9040) ["name"]=> string(8) "Coupe GK"
["value"]=> string(8) "coupe-gk" ["count"]=> int(0)
}
}
}
}
This would lead me to believe that you're after the id at:
<object>["_sft_product_cat"]["active_terms"][0]["id]
or
<object>[0][4][0][0]

PHP array sorting associative array using a specific key value

I have an array which need to sort using a key value of "odbyx"
Here is the array var_dump
array(12) {
["id"]=> array(7) {
[0]=> string(1) "8"
[1]=> string(1) "7"
[2]=> string(1) "3"
[3]=> string(1) "6"
[4]=> string(1) "5"
[5]=> string(1) "2"
[6]=> string(1) "1"
}
["subject"]=> array(7) {
[0]=> string(14) "ticke tick sbj"
[1]=> string(13) "new tick test"
[2]=> string(15) "fdsfdsfdsfdsfds"
[3]=> string(12) "test subject"
[4]=> string(4) "test"
[5]=> string(4) "test"
[6]=> string(12) "test subject"
}
["msg"]=> array(7) {
[0]=> string(9) "test+tick"
[1]=> string(4) "test"
[2]=> string(9) "dfdsfdsfd"
[3]=> string(12) "test+tcikets"
[4]=> string(4) "test"
[5]=> string(12) "test+message"
[6]=> string(7) "tssssss"
}
["department"]=> array(7) {
[0]=> string(10) "Technician"
[1]=> string(5) "Admin"
[2]=> string(5) "Admin"
[3]=> string(10) "Technician"
[4]=> string(10) "Technician"
[5]=> string(5) "Admin"
[6]=> string(5) "Admin"
}
["priorety"]=> array(7) {
[0]=> string(3) "Low"
[1]=> string(6) "Normal"
[2]=> string(3) "Low"
[3]=> string(3) "Low"
[4]=> string(4) "High"
[5]=> string(6) "Normal"
[6]=> string(3) "Low"
}
["status"]=> array(7) {
[0]=> string(4) "open"
[1]=> string(8) "answered"
[2]=> string(8) "answered"
[3]=> string(4) "open"
[4]=> string(4) "open"
[5]=> string(4) "open"
[6]=> string(6) "closed"
}
["dateAded"]=> array(7) {
[0]=> string(19) "2017-10-01 12:34:56"
[1]=> string(19) "2017-09-27 13:41:09"
[2]=> string(19) "2017-09-17 13:53:04"
[3]=> string(19) "2017-09-25 15:00:48"
[4]=> string(19) "2017-09-23 10:41:24"
[5]=> string(19) "2017-09-17 13:31:56"
[6]=> string(19) "2017-09-17 12:37:22"
}
["dateClosed"]=> array(7) {
[0]=> string(19) "0000-00-00 00:00:00"
[1]=> string(19) "0000-00-00 00:00:00"
[2]=> string(19) "0000-00-00 00:00:00"
[3]=> string(19) "0000-00-00 00:00:00"
[4]=> string(19) "0000-00-00 00:00:00"
[5]=> string(19) "2017-09-30 13:41:09"
[6]=> string(19) "2017-09-17 13:40:53"
}
["dateActivity"]=> array(7) {
[0]=> string(19) "2017-10-01 12:34:56"
[1]=> string(19) "2017-10-01 07:49:20"
[2]=> string(19) "2017-09-26 10:35:36"
[3]=> string(19) "2017-09-25 15:00:48"
[4]=> string(19) "2017-09-23 10:41:24"
[5]=> string(19) "2017-09-17 13:41:21"
[6]=> string(19) "2017-09-17 13:40:53"
}
["userId"]=> array(7) {
[0]=> string(1) "4"
[1]=> string(1) "4"
[2]=> string(1) "3"
[3]=> string(1) "4"
[4]=> string(1) "7"
[5]=> string(1) "3"
[6]=> string(1) "2"
}
["res"]=> string(4) "true"
["odbyx"]=> array(7) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
[3]=> int(2)
[4]=> int(3)
[5]=> int(3)
[6]=> int(3)
}
}
Logic behind the array
$array = array
(
"id" => $id,
"subject" => $subject,
"msg" => $msg,
"department" => $department,
"priorety" => $priorety,
"status" => $status,
"dateAded" => $dateAded,
"dateClosed" => $dateClosed,
"dateActivity" => $dateActivity,
"userId" => $userId,
"res" => $res,
"odbyx"=>$odbyx
);
I tried sort using below code but it seems not working
array_multisort(array_column($array, 'odbyx'), SORT_DESC, $array);
odbyx field hold a priority values (1,2,3).
i need to sort main array using that values, so i can display top priority fields at the beginning soo on a table
I want to sort the $array using "odbyx" descending order
Example Output of id array, the other arrays also need to sort at once.
["id"]=> array(7) { [0]=> string(1) "6" [1]=> string(1) "5" [2]=> string(1) "4" [3]=> string(1) "3" [4]=> string(1) "7" [5]=> string(1) "6" [6]=> string(1) "8" }
proper use of usort
See also: Sort Multi-dimensional Array by Value
your example is invalid
Expected first entry in result: 0 => '6'
Possible interpretation odbyx-index == id-index
Should indices in odbyx match to indices in id?
i.e.: $array['id'][3] should be sorted by $array['odbyx'][3]
If this is the case, then your provided code should either yield 0 => '8' for the first index (odbyx 1 higher-priority than 3), or 0 => '1' (3 is higher).
Possible interpretation odbyx-index == id-value
Should the index in odbyx match to the id values in id?
i.e.: The value of $array['odbyx'][1] determines the sort for $array['id'][6] = '1'
In this case, the result should be 0 => '2'
None of these possible interpretations even match the very first result in your example. The lesson here is specification, i.e.: carefully define and describe the specific conditions required to solve your problem, on stackoverflow or anywhere else.
Here's a place to start
Since the problem you are asking to be solved is complex, poorly defined, would require a significant amount of coding and testing, and has significant performance implications, I'll leave you with this tidbit of a solution to one of the impossible interpretations above. Good luck.
Class SimpleSorter
{
private $orderBy;
private $sortMe;
public static function sortByIndexedOrderField(array $sortMe, array $byMe)
{
$sorter = new self($sortMe);
return $sorter->applyIndexedOrder($byMe);
}
public function __construct(array $sortMe)
{
$this->sortMe = $sortMe;
}
public function applyIndexedOrder(array $byMe): array
{
$this->orderBy = $byMe;
$keys = array_keys($this->sortMe);
// sort, first by odbyx, then by value
usort($keys, function($a,$b){
$odbyx = 0;
if (array_key_exists($a, $this->orderBy) && array_key_exists($b, $this->orderBy)) {
$odbyx = $this->orderBy[$b] <=> $this->orderBy[$a];
}
if (0 !== $odbyx) {
return $odbyx;
}
return $this->sortMe[$a] <=> $this->sortMe[$b];
});
// reorder by new key order
$result = [];
foreach($keys as $key) {
$result[$key] = $this->sortMe[$key];
}
return $result;
}
}
$array = [];
$array["id"] = [
0 => '8',
1 => '7',
2 => '3',
3 => '6',
4 => '5',
5 => '2',
6 => '1',
];
$array["odbyx"] = [
0 => 1,
1 => 2,
2 => 3,
3 => 2,
4 => 3,
5 => 3,
6 => 3,
];
$idsSorted = SimpleSorter::sortByIndexedOrderField($array["id"], $array["odbyx"]);
print_r($idsSorted);

Looking to create an associative array

I'm looking for a solution to create an associative array from an flat array data in foreach loop:
What i have is a csv/xls file that has header on first row and data in next rows.
Row1: header
Row2,3,4,5: data
the array looks:
array(3) {
[0]=>
array(7) {
[0]=>
string(3) "country"
[1]=>
string(7) "state"
[2]=>
string(3) "city"
[3]=>
string(5) "name"
[4]=>
string(4) "address"
[5]=>
string(6) "gender"
[6]=>
string(6) "status"
}
[1]=>
array(7) {
[0]=>
string(12) "Argentina"
[1]=>
string(12) "Corrientes"
[2]=>
string(12) "Corrientes"
[3]=>
string(12) "Jorge"
[4]=>
string(12) "Avenida Avellaneda 12"
[5]=>
string(12) "Masculino"
[6]=>
string(12) "Activo"
}
[2]=>
array(7) {
[0]=>
string(12) "Argentina"
[1]=>
string(12) "Chaco"
[2]=>
string(12) "Resistencia"
[3]=>
string(12) "Mariano"
[4]=>
string(12) "Avenida Peron 12"
[5]=>
string(12) "Masculino"
[6]=>
string(12) "Activo"
}
}
The result i need to get at the end is:
array(2) {
[0]=>
array(7) {
['country']=>
string(12) "Argentina"
['state']=>
string(12) "Corrientes"
['city']=>
string(12) "Corrientes"
['name']=>
string(12) "Jorge"
['address']=>
string(12) "Avenida Avellaneda 12"
['gender']=>
string(12) "Masculino"
['status']=>
string(12) "Activo"
}
[1]=>
array(7) {
['country']=>
string(12) "Argentina"
['state']=>
string(12) "Chaco"
['city']=>
string(12) "Resistencia"
['name']=>
string(12) "Mariano"
['address']=>
string(12) "Avenida Peron 12"
['gender']=>
string(12) "Masculino"
['status']=>
string(12) "Activo"
}
}
$array = $your_flat_array;
for ($i = 1; $i < count($array); $i++) {
$new_array[$i-1] = [];
foreach ($array[$i] as $key => $value) {
$new_array[$i-1][$array[0][$key]] = $value;
}
}
print_r($new_array);
create a multidimensional array from an flat array
You already have a multidimensional array, because you got arrays in an array.
What you can do in this specific case is to use array_splice() in combination with array_combine().
Try this:
$oldArray = array(
array( "country", "state", "city", "name" ),
array( "Argentina", "Corrientes", "Corrientes", "Jorge" ),
array( "Argentina", "Chaco", "Resistencia", "Mariano" )
);
$newArray = array_splice( $oldArray, 1 );
foreach( $newArray as $index => $array ) {
$newArray[$index] = array_combine( $oldArray[0], $array );
}
echo "<pre>";
var_dump( $newArray );
OUTPUT:
array(2) {
[0]=>
array(4) {
["country"]=>
string(9) "Argentina"
["state"]=>
string(10) "Corrientes"
["city"]=>
string(10) "Corrientes"
["name"]=>
string(5) "Jorge"
}
[1]=>
array(4) {
["country"]=>
string(9) "Argentina"
["state"]=>
string(5) "Chaco"
["city"]=>
string(11) "Resistencia"
["name"]=>
string(7) "Mariano"
}
}
All you have to do is remove the first item (header row) from your array:
array_splice($yourArray, 0, 1);

Merge array where duplicate in multidimensional array

I've been trying to merge this array ONLY WHERE $array[4] exists more than one time, example: $array[4] == 'red' exactly twice. How can I merge only those arrays while keeping the others? I have made several attempts at this and I am willing to include my efforts if asked.
Consider this array:
array(3) {
[0]=>
array(5) {
[0]=>
string(3) "UID"
[1]=>
string(3) "532"
[2]=>
string(1) "2"
[3]=>
string(9) "Domain(s)"
[4]=>
string(20) "red"
}
[1]=>
array(5) {
[0]=>
string(3) "UID"
[1]=>
string(3) "532"
[2]=>
string(7) "License"
[3]=>
string(3) "Fee"
[4]=>
string(20) "red"
}
[2]=>
array(5) {
[0]=>
string(3) "UID"
[1]=>
string(3) "536"
[2]=>
string(7) "License"
[3]=>
string(3) "Fee"
[4]=>
string(16) " University Test"
}
}
TRYING TO ACHIEVE:
array(3) {
[0]=>
array(5) {
[0]=>
string(3) "UID"
[1]=>
string(3) "532"
[2]=>
string(1) "2"
[3]=>
string(9) "Domain(s)"
[4]=>
string(20) " red"
[5]=>
string(3) "Fee"
[6]=>
string(7) "License"
}
[1]=>
array(5) {
[0]=>
string(3) "UID"
[1]=>
string(3) "536"
[2]=>
string(7) "License"
[3]=>
string(3) "Fee"
[4]=>
string(16) " University Test"
}
}
foreach ($test as $item) {
if (!isset($merged[$item[4]])) {
// add the item to the merged array using key=$item[4]
$merged[$item[4]] = $item;
} else {
// merge the item with the item that is already in the array at key=$item[4]
$merged[$item[4]] = array_unique(array_merge($merged[$item[4]], $item));
// array_unique is necessary because array_merge will not overwrite numeric keys
}
}
// convert the keys back to numeric (if you care to)
$merged = array_values($merged);

PHP: sort array by own value pattern

I have an array :
array(1) { ["myarr"]=> array(5) {
[0]=> array(2) { ["symbol"]=> string(6) "EUR" ["desc"]=> string(6) "da" }
[1]=> array(2) { ["symbol"]=> string(6) "USD" ["desc"]=> string(6) "adad" }
[2]=> array(2) { ["symbol"]=> string(6) "CHF" ["desc"]=> string(6) "das23" }
[3]=> array(2) { ["symbol"]=> string(6) "GBP" ["desc"]=> string(6) "dd12" }
[4]=> array(2) { ["symbol"]=> string(6) "NOR" ["desc"]=> string(6) "233" }
}
}
Now i need sort array by symbol in order: NOR, USD, EUR, CHF , GBP
So i wrote callback function
uasort($myarr , 'sort_myarr')
function sort_myarr($a, $b) {
static $sizes = array( 'NOR' => 0, 'USD' => 1, 'EUR' => 2, 'CHF' => 3, 'GBP' => 4);
return $sizes[$a] - $sizes[$b];
}
But doesn't sort :(
Your sort function should read
return $sizes[$a['symbol']] - $sizes[$b['symbol']];
The arguments $a and $b are items from inside your array, which in this case are themselves arrays. You have to grab the appropriate element from inside them to sort with.

Categories