Sorting multidimensional array by two user defined values - php

I need to sort a multidimensional array by two values.
For example in the array will be 4 keys.
Array(
Array
(
[0] => 4B642D022980E5EBAA7CF4B6E1CC93769921CB42
[1] => downloading
[2] => Title
[3] => 60
)
Array
(
[0] => 4B642D022980E5EBAA7CF4B6E1CC93769921CB42
[1] => downloading
[2] => Title
[3] => 30
)
Array
(
[0] => 4B642D022980E5EBAA7CF4B6E1CC93769921CB42
[1] => paused
[2] => Title
[3] => 30
)
Array
(
[0] => 4B642D022980E5EBAA7CF4B6E1CC93769921CB42
[1] => completed
[2] => Title
[3] => 100
)
)
Is there a way I can sort the array so that it would sort the arrays with key completed first, then downloading second, then paused third and then also sort the arrays containing downloading and paused from 100 down to 0 by the 3 key?
Desired output would be
Array(
Array
(
[0] => 4B642D022980E5EBAA7CF4B6E1CC93769921CB42
[1] => completed
[2] => Title
[3] => 100
)
Array
(
[0] => 4B642D022980E5EBAA7CF4B6E1CC93769921CB42
[1] => downloading
[2] => Title
[3] => 60
)
Array
(
[0] => 4B642D022980E5EBAA7CF4B6E1CC93769921CB42
[1] => downloading
[2] => Title
[3] => 30
)
Array
(
[0] => 4B642D022980E5EBAA7CF4B6E1CC93769921CB42
[1] => paused
[2] => Title
[3] => 30
)
)

uksort is what you need.
It is a sort that lets you define you own callback function.
This callback function is then used by uksort to reorder the array.
You need to write a function that will sort an array based on two criterias.
The first one is the alphabetical order of the field at indice 1 of your array (which contains the words completed, downloading, ...) and in case of tie you would then use the field at indice 3 of your array and sort in decreasing order.
Finally, you will need to pass the function you created as a parameter to uksort.
Hope it helps ! :)

You need to reformat your array and use array_multisort. It will also make thinks more readable:
<?php $ar = Array(
Array(
"id" => "4B642D022980E5EBAA7CF4B6E1CC93769921CB42",
"status" => "completed",
"title" => "Title",
"rank" => "100",
),
Array
(
"id" => "4B642D022980E5EBAA7CF4B6E1CC93769921CB42",
"status" => "downloading",
"title" => "Title",
"rank" => "60",
),
Array
(
"id" => "4B642D022980E5EBAA7CF4B6E1CC93769921CB42",
"status" => "downloading",
"title" => "Title",
"rank" => "30",
),
Array
(
"id" => "4B642D022980E5EBAA7CF4B6E1CC93769921CB42",
"status" => "paused",
"title" => "Title",
"rank" => "30",
),
);
var_dump($ar);
foreach ($ar as $key => $row) {
$status[$key] = $row['status'];
$rank[$key] = $row['rank'];
}
array_multisort($status, SORT_ASC, $rank, SORT_DESC, $ar);
var_dump($ar);

$array = [
[
'4B642D022980E5EBAA7CF4B6E1CC93769921CB42',
'downloading',
'Title',
'60',
],
[
'4B642D022980E5EBAA7CF4B6E1CC93769921CB42',
'downloading',
'Title',
'30',
],
[
'4B642D022980E5EBAA7CF4B6E1CC93769921CB42',
'paused',
'Title',
'30',
],
[
'4B642D022980E5EBAA7CF4B6E1CC93769921CB42',
'completed',
'Title',
'100',
]
];
usort($array, function($a, $b) {
if ($a[1] == $b[1]) {
if ($a[3] == $b[3]) {
return 0;
}
return ($a[3] > $b[3]) ? -1 : 1;
}
$status = ['completed', 'downloading', 'paused'];
foreach ($status as $st) {
if ($a[1] == $st)
return -1;
if ($b[1] == $st)
return 1;
}
return 0;
});
var_dump($array);

Related

PHP : Add lowest value from duplicate records of array

I want to remove duplicate record which is highest value in array.
Array :
Array
(
[0] => Array
(
[id] => 1
[number] => 123
[price] => 6
)
[1] => Array
(
[id] => 2
[number] => 456
[price] => 6
)
[2] => Array
(
[id] => 3
[number] => 123
[price] => 5
)
)
Expected Result :
Array
(
[0] => Array
(
[id] => 2
[number] => 456
[price] => 6
)
[1] => Array
(
[id] => 3
[number] => 123
[price] => 5
)
)
number is duplicate field and after that need to compare price. Which will be lower that will be display. Rest of all should be removed.
What I tried :
$lowest = min($myArray);
$result = array_filter($myArray, function($value, $key) use ($lowest) {
return $value === $lowest;
}, ARRAY_FILTER_USE_BOTH);
How can i do that?
UPDATE :
#Daniel Dez solution is almost working. I used 3rd solution of him. But, It should be working like this.
For ex : number 123 is duplicate records now it's lowest price is 2. Then, it should be display rest of 123 number's array element remove.
Array :
$data = [
[
"id" => 1,
"number" => 123,
"price" => 2,
],
[
"id" => 2,
"number" => 456,
"price" => 6,
],
[
"id" => 3,
"number" => 123,
"price" => 5,
],
[
"id" => 4,
"number" => 123,
"price" => 11,
],
[
"id" => 5,
"number" => 456,
"price" => 5,
],
[
"id" => 6,
"number" => 123,
"price" => 5,
]
];
Expected Output :
Array
(
[0] => Array
(
[id] => 1
[number] => 123
[price] => 2
)
[1] => Array
(
[id] => 2
[number] => 456
[price] => 5
)
)
please help me.
Thanks.
Data:
$numbers = array_unique(array_column($data, 'number'));
usort($data, function ($a, $b) {
return $a['price'] - $b['price'];
});
$result = [];
foreach ($numbers as $number) {
foreach ($data as $item) {
if ($item['number'] == $number) {
break;
}
}
$result[] = $item;
}
print_r($result);

Merge first array particular key and value into second array

I have 2 array
$arr1 = Array (
[0] => Array ( [customer_id] => 1 [Expire] => 2019-05-14 [paid] => 1 )
[1] => Array ( [customer_id] => 2 [Expire] => 2019-06-20 [paid] => 0 ))
and
$arr2 = Array (
[0] => Array ( [id] => 3943 [customer_id] => 1 [Expire] => 2019-05-14 )
[1] => Array ( [id] => 3944 [customer_id] => 1[Expire] => 2019-05-14 )
[2] => Array ( [id] => 4713 [customer_id] => 2 [Expire] => 2019-06-20 )
)
and try to put first array key and value [paid]=>1 or 0 in second array if customer id and expire match like
Array (
[0] => Array ( [id] => 3943 [customer_id] => 1 [Expire] => 2019-05-14 [paid] => 1)
[1] => Array ( [id] => 3944 [customer_id] => 1 [Expire] => 2019-05-14 [paid] => 1)
[2] => Array ( [id] => 4713 [customer_id] => 2 [Expire] => 2019-06-20 [paid] => 0)
)
I try to merge array in php but not get exact what i want. Is there any php function to do it?.
Loop your second array $arr2, and find the index of the first array $arr1 where the column customer_id is the same as in the current iteration of $arr2. array_search() returns that index, which we can then use to fetch the paid index of that array. Then we append it to our array $arr2, by doing $a['paid'] = $paid;.
Since we loop the array by reference (the & before $a in the loop), the changes we make to it, will be applied back to the original array.
foreach ($arr2 as &$a) {
$customerID = $a['customer_id']; // This customer ID
$arr1_key = array_search($customerID, array_column($arr1, 'customer_id')); // Find the index of this customerID in the first array
$paid = $arr1[$arr1_key]['paid']; // Find the paid value matching that customer ID
$a['paid'] = $paid;
}
Live demo at https://3v4l.org/Meqtu
Update
If you need it to match the ID as well as the expiration date, then use array_filter() to fetch the array-element within $arr1 that matches the date and the ID. Using reset(), we use the first element in that array.
foreach ($arr2 as &$a) {
// Find the sub-array of $arr1 that matches this array's date and ID
$arr1_match = array_filter($arr1, function($v) use ($a) {
return $v['customer_id'] == $a['customer_id'] && $v['Expire'] == $a['Expire'];
});
// Get the first element from the result
$paid = reset($arr1_match)['paid'];
// Append the paid-value to this array (done by reference)
$a['paid'] = $paid;
}
Live demo at https://3v4l.org/mov6d
sometimes things can be done in hard way:)
<?php
$arr1 = [
['customer_id' => 1, 'Expire' => '2019-05-14', 'paid' => 1],
['customer_id' => 2, 'Expire' => '2019-06-20', 'paid' => 0],
];
$arr2 = [
['id' => 3943, 'customer_id' => 1, 'Expire' => '2019-05-14'],
['id' => 3944, 'customer_id' => 1, 'Expire' => '2019-05-14'],
['id' => 3945, 'customer_id' => 2, 'Expire' => '2019-05-14'],
['id' => 4713, 'customer_id' => 2, 'Expire' => '2019-06-20'],
];
foreach ($arr2 as &$item2) {
foreach ($arr1 as $item1) {
if (
$item2['customer_id'] === $item1['customer_id']
&& $item2['Expire'] === $item1['Expire']
) {
$item2['paid'] = $item1['paid'];
break;
}
}
}
unset($item2);
var_dump($arr2);
If you cannot change the layout of the first array I think it will be best to first create an intermediate array that keeps a record of all expire dates for every customer.
The following implementation does not require you to use a nested loop.
<?php
$arr1 = [
['customer_id' => 1, 'Expire' => '2019-05-14', 'paid' => 1],
['customer_id' => 2, 'Expire' => '2019-06-20', 'paid' => 0],
];
$arr2 = [
['id' => 3943, 'customer_id' => 1, 'Expire' => '2019-05-14'],
['id' => 3944, 'customer_id' => 1, 'Expire' => '2019-05-14'],
['id' => 3945, 'customer_id' => 2, 'Expire' => '2019-05-14'],
['id' => 4713, 'customer_id' => 2, 'Expire' => '2019-06-20'],
];
// Create a list of all paid, expiry dates, keyed by customer_id
$payed = [];
foreach ($arr1 as $item) {
if (!isset($payed[$item['customer_id']])) {
$payed[$item['customer_id']] = [];
}
$payed[$item['customer_id']][] = $item['Expire'];
}
// Lookup the customer and expire date for every entry
$arr2 = array_map(function($item) use ($payed) {
$item['paid'] = in_array($item['Expire'], $payed[$item['customer_id']] ?? []);
return $item;
}, $arr2);
Result:
Array
(
[0] => Array
(
[id] => 3943
[customer_id] => 1
[Expire] => 2019-05-14
[paid] => 1
)
[1] => Array
(
[id] => 3944
[customer_id] => 1
[Expire] => 2019-05-14
[paid] => 1
)
[2] => Array
(
[id] => 3945
[customer_id] => 2
[Expire] => 2019-05-14
[paid] =>
)
[3] => Array
(
[id] => 4713
[customer_id] => 2
[Expire] => 2019-06-20
[paid] => 1
)
)
See demo
This can fix the issue :
$arr1 = array(
["customer_id"=>1,"Expire"=> "2019-05-14", "paid"=>1],
["customer_id"=>2,"Expire"=> "2019-06-20", "paid"=>0]
);
$arr2 = array(
["id"=>3943, "customer_id"=>1,"Expire"=> "2019-05-14"],
["id"=>3944,"customer_id"=>2,"Expire"=> "2019-06-20"],
["id"=>4713,"customer_id"=>1,"Expire"=> "2019-05-14"]
);
$result= array();
function getRowByCustomerID($id, $array){
foreach($array as $value){
if($value['customer_id'] ==$id){
return $value;
}
}
return null;
}
foreach($arr2 as $subarr){
$object = getRowByCustomerID($subarr['customer_id'],$arr1 );
if(!is_null($object)){
$object['id']=$subarr['id'];
$result[]= $object;
}
}
var_dump($result);
the output is similar to what you are looking for :
array(3) {
[0]=>
array(4) {
["customer_id"]=>
int(1)
["Expire"]=>
string(10) "2019-05-14"
["paid"]=>
int(1)
["id"]=>
int(3943)
}
[1]=>
array(4) {
["customer_id"]=>
int(2)
["Expire"]=>
string(10) "2019-06-20"
["paid"]=>
int(0)
["id"]=>
int(3944)
}
[2]=>
array(4) {
["customer_id"]=>
int(1)
["Expire"]=>
string(10) "2019-05-14"
["paid"]=>
int(1)
["id"]=>
int(4713)
}
}

Deep Associative Array to adjacent mysql table

Been fighting the whole night. Giving up. I have an adjacent table in mysql:
id, parentid,name,design,path,sort
The depth is maximum four and using mysql query, I print out the results to UL list successfully. From there, items are added, sorted and edited as well as removed. Then when button is clicked, I send the result back to php. The data been sent is JSON and it does get recieved.
json_decode() gives the following sample:
Array ( [0] => Array ( [cls] => [path] => # [id] => 1 [name] =>BLOCKA ) [1] => Array ( [cls] => [path] => # [id] => 2 [name] => BLOCKB [children] => Array ( [0] => Array ( [cls] => [path] => # [id] => 3 [name] => CLASSB1 [children] => Array ( [0] => Array ( [cls] => [path] => # [id] => 7 [name] => CLASSB12 ) ) ) [1] => Array ( [cls] => [path] => # [id] => 4 [name] => CLASSSB13 [children] => Array ( [0] => Array ( [cls] => [path] => # [id] => 5 [name] => CLASSB4 ) [1] => Array ( [cls] => [path] => # [id] => 6 [name] => CLASSB5 ) ) ) ) ) )
Graphically:
BLOCKA
BLOCKB
CLASSB1
CLASSB3
...
I am using jquery.nested
Now my problem is looping through the array, getting id of the parent then add child.
The closest I came with is
function dissect($blocks) {
if (!is_array($blocks)) {
echo $blocks;
return;
}
foreach($blocks as $block) {
dissect($block);
}
}
It does process each element but not in the way I want. Sorry for my broken english...any help would be appreciated.
First iterate through blocks getting the parent, if children exists in parent block, loop through the children.
There might be other better way to implement this, you can try below code:
$blocks = array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 1,
"name" =>"BLOCKA",
)
),
"1" => array (
"cls" => "",
"path" => array(
"id" => 2,
"name" => "BLOCKB" ,
"children" => array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 3,
"name" => "CLASSB1" ,
"children" => array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 7,
"name" => "CLASSB12" ,
),
),
),
),
),
"1" => array (
"cls" => "",
"path" => array(
"id" => 4,
"name" => "CLASSSB13" ,
"children" => array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 5,
"name" => "CLASSB4" ,
),
),
"1" => array (
"cls" => "",
"path" => array(
"id" => 6,
"name" => "CLASSB5",
),
),
),
),
),
),
),
),
) ;
echo "<pre>";
/*loop through blocks*/
foreach ($blocks as $key => $block) {
echo $block['path']['name'].'<br/>'; /* echo parent*/
if (isset($block['path']['children'])) {
loopChildren($block['path']['children']); /* children loop*/
}
}
/*Loop through childrens*/
function loopChildren($childrens, $prefix = '-')
{
foreach ($childrens as $key => $child) {
getChild($child, $prefix);
}
}
/*Get the child and loop sub-children if exist*/
function getChild($child, $prefix='-')
{
echo $prefix. $child['path']['name'].'<br/>'; /*echo child*/
if (isset($child['path']['children'])) {
$prefix .= '-';
loopChildren($child['path']['children'], $prefix); /* sub-children loop*/
}
}
echo "</pre>";
The output:
BLOCKA
BLOCKB
-CLASSB1
--CLASSB12
-CLASSSB13
--CLASSB4
--CLASSB5
thanks for your tip. It guided me to an answer that worked for me. I ended up using two functions. The error was "index out of bound"...here is what I did now...with calls to the mysql table:
$response = json_decode($_POST['s'], true); // decoding received JSON to array
if(is_array($response)){
//start saving now
$order=1;
foreach ($response as $key => $block) {
//0 is for blocks: no parent id needed
$parentid=$this->Blocks_model->insertblock($block['name'],$block['cls'],0,$block['path'],$order);
if (isset($block['children'])) {
$this->childblocks($parentid,$block['children']);
}
$order++;
}
}
private function childblocks($parentid,$e){
$order=1;
foreach ($e as $key => $block) {
$parentid=$this->Blocks_model->insertblock($block['name'],$block['cls'],0,$block['path'],$order);
if (isset($block['children'])) {
$this->childblocks($parentid,$block['children']);
}
$order++;
}
}

Make array unique in multidimensional array php codeigniter

I have this array
Array (
[0] => Array
(
[0] => stdClass Object
(
[id] => 226
[user_id] => 1
[name] => Eden Corner Tub by Glass - $2099
)
[1] => stdClass Object
(
[id] => 225
[user_id] => 1
[name] => Blue Quilted Leather Jacket by Minusey - $499
)
[2] => stdClass Object
(
[id] => 222
[user_id] => 1
[name] => Darling New Bathtub by Duravit - $6300
)
)
[1] => Array
(
[0] => stdClass Object
(
[id] => 226
[user_id] => 1
[name] => Eden Corner Tub by Glass - $2099
)
[1] => stdClass Object
(
[id] => 229
[user_id] => 1
[name] => Batman Tumbler Golf Cart - $50000
)
[2] => stdClass Object
(
[id] => 228
[user_id] => 1
[name] => Swirlio Frozen Fruit Dessert Maker - $60
)
) )
I have an array of products that I need to make sure are unique.
Need to make this array unique by id. These array are generated by pushing value.
I'm trying to solve this for more than a week now, but I dont get it to work. I know it should be easy...but anyway - I don't get it :D
Try this:
$array = array(
0 => array(
"name" => "test",
"id" => 4
),
1 => array(
"name" => "test2",
"id" => 152
),
2 => array(
"name" => "test2",
"id" => 152
)
);
$newArray = array();
foreach($array as $value) {
$newArray[$value['id']]['name'] = $value['name'];
$newArray[$value['id']]['id'] = $value['id'];
}
foreach($array as $key=>$inner_array)
{
foreach($array as $key_again=>$array_again)
{
if($key != $key_again)
{
if($inner_array['name'] != $array_again['name'] AND $inner_array['id'] != $array_again['id'])
{
//its okay
}
else
{
unset($array[$key]);
}
}
}
}
Not sure how the arrays are generated, but, if you can change that, you could set the array keys to the IDs directly and check if the id is already set.
Otherwise, you can do the following:
$unique = array();
foreach( $array as $values ) {
if( ! isset( $unique[$values['id']] ) ) {
$unique[$values['id']] = $values;
}
}
This will make your array unique:
$array = array(
0 => array(
"name" => "test",
"id" => 4
),
1 => array(
"name" => "test2",
"id" => 152
),
2 => array(
"name" => "test2",
"id" => 152
) );
$result = array();
$index = array();
foreach($array as $i => $elem) {
if(!isset($index[$elem['id']])) {
$result[$i] = $elem;
$index[$elem['id']] = 1;
}
}
echo var_export($result);
Output:
array (
0 =>
array (
'name' => 'test',
'id' => 4,
),
1 =>
array (
'name' => 'test2',
'id' => 152,
),
)
This will work. It could be considered more clean than a for loop, but I'm not sure about performance.
$array = [
[ "name" => "test", "id" => 4 ],
[ "name" => "test2", "id" => 152 ],
[ "name" => "test2", "id" => 152 ]
];
array_walk($array, function(&$item, $idx) use($array){
$matches = array_slice(array_keys($array, $item), 1);
if (in_array($idx, $matches)) {
$item = false;
}
});
$array = array_filter($array);
Edit Since you updated the data set to work with, you would need to flatten it 1 level:
$array = call_user_func_array('array_merge', $array);

Merge two array with specific id, then , order this new array alphabetically

I have to array and I want to merge this two array with a main key ( ID ) , and I would like to order alphabetically this NEW array ( the lastname field )
Array (
[0] =>
Array ( [id] => 172
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => accepted
)
[1] =>
Array (
[id] => 173
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => pending
) )
And this array
Array (
[1217330 ] =>
Array ( [firstname] => Philip
[lastname] => Audet
[birthdate] => 1995-07-17
[id] => 1217330
)
[232323] =>
Array ( [firstname] => Frédéric
[lastname] => Bouchard-Dubé
[birthdate] => 1995-07-17
[id] => 232323
)
And I would like to have this
[0] =>
Array ( [id] => 172
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => accepted
[firstname] => Philip
[lastname] => Audet
)
[1] =>
Array (
[id] => 173
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => pending
[firstname] => Philip
[lastname] => Audet
) )
I wont want to have the birthdate index for THIS array, I only want to get the firstname and the lastname from the second array. So I want to math the index USER_ID ( first_table) with ID (second table). I also want to order this new table alphabetically with the lastname (in my exemple, I don't need to sort it alphabetically, but I will need to do this )
Can some one can help me please ? Thx
Thx
This is doing what you are looking for. As your example is out of context you might need to take some different approaches, but I hope it will help you get the task done.
$behaviour = array(
array(
'id' => 172,
'user_id' => 1217330,
'behaviour_action_id' => 97,
'state' => 'accepted'
),
array(
'id' => 173,
'user_id' => 232323,
'behaviour_action_id' => 97,
'state' => 'pending'
),
);
$users = array(
1217330 => array(
'firstname' => 'Philip',
'lastname' => 'Audet',
'birthdate' => '1995-07-17',
'id' => 1217330
),
232323 => array(
'firstname' => 'Frédéric',
'lastname' => 'Bouchard-Dubé',
'birthdate' => '1995-07-17',
'id' => 232323
),
);
//we will collect the data in a new array
$combined = array();
//now we loop through all behaviours
foreach($behaviour as $key => $behaviourData){
//we look up the data which belongs to the user of this behaviour
$wantedUserData = $users[$behaviourData['user_id']];
//birthdate is unwanted
unset($wantedUserData['birthdate']);
//merge data
$combined[] = array_merge($behaviourData, $wantedUserData);
}
//order array
usort($combined,'cmp');
//voilà!
var_dump($combined);
//Comparison function used in usort above
function cmp($a, $b){
if ($a['lastname'] == $b['lastname']){
return 0;
}
return ($a['lastname'] < $b['lastname']) ? -1 : 1;
}
$arr1 = array (
array("id"=>172, "user_id"=>1217330, "behaviour_action_id"=>97, "state"=>"accepted"),
array("id"=>173, "user_id"=>1217330, "behaviour_action_id"=>97, "state"=>"pending")
);
$arr2 = array(
"1217330" => array(
"firstname" => "Philip",
"lastname" => "Audet",
"birthdate" => "1995-07-17",
"id" => 1217330
),
"232323" => array (
"firstname" => "Frédéric",
"lastname" => "Bouchard-Dubé",
"birthdate" => "1995-07-17",
"id" => 232323
)
);
foreach($arr1 as $arr) {
$extra = $arr2[$arr["user_id"]];
unset($extra["birthdate"]);
$newarray[] = array_merge($extra, $arr);
}
print_r($newarray);
this one? (assuming $arr1 and $arr2 the given arrays)
$arr3 = array();
foreach($arr1 as $key=>$val) {
$arr3[$key] = $val;
$arr3[$key]["firstname"] = $arr2[$val["user_id"]]["firstname"];
$arr3[$key]["lastname"] = $arr2[$val["user_id"]]["lastname"];
}
echo "<pre>";
print_r($arr3);
echo "</pre>";
Well, I don't want to give a cooked-up code but this algorithm will do the job:
1) Loop through first array and create another array with user_id as key. like
$new_array[$array['user_id']] = array($array['id'], $array['state']...);
2) Loop through second array and unset() the key birthdate.
3) Use array_merge_recursive() and merge the two arrays.

Categories