Sort an array from another array values in PHP - php

I got an $actions array, and $actions_used array.
$actions_used looks like this:
array(1) {
[2]=>
string(1) "18"
[5]=>
string(1) "33"
}
$actions looks like this:
array(3) {
[1]=>
string(9) "Withdraw"
[2]=>
string(13) "Deposit"
[5]=>
string(10) "Blabla"
}
I would like to sort $actions based on the value that is in $actions_used.
The correct output would be for $actions:
array(3) {
[5]=>
string(9) "Blabla"
[2]=>
string(13) "Deposit"
[1]=>
string(10) "Withdraw"
}
Why? Because array key 5, "Blabla" has the biggest value "33" and then comes array key "2" which has value 18 and then at last comes array key 1, "Withdraw" which have 0 (no value)
How can this be done?

This should do the trick.
$sorted_actions = array();
asort($actions_used);
foreach($actions_used AS $key => $amount) {
$sorted_actions[] = array('amount' => $amount, 'action' => $actions[$key]);
unset($actions[$key]);
}
$sorted_actions = $sorted_actions + $actions;

How would something like this work?
arsort($action_used);
foreach ($action_used as $k => $v) {
$newArray[$k] = $actions[$k];
unset($action_used[$k];
}
$newArray = array_merge($newArray, $action_used);

I think you could sort the second array with uksort and actually compare the values from the first array in the custom comparer
e.g.:
uksort($arr2, function($i1, $i2) {
return $arr1[$i1] - $arr1[$i2];
});

Related

Combing matched keys in an array

Edited
I get the combined item_ids now, but not the single item_ids.
I have an array with three keys.
$searchArray = {
[0]=> array(3) {
["keyword"]=> string(7) "history"
["url"]=> string(7) "history"
["item_id"]=> string(2) "16"
}
[1]=> array(3) {
["keyword"]=> string(4) "past"
["url"]=> string(4) "past"
["item_id"]=> string(2) "16"
}
[89]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "34"
}
[93]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "35"
}
I want to combine the options that have the same keyword/url.
Just need to check if keyword matches.
The final format needs to be something that jquery autocomplete can accept, where I can assign the text to keyword and the value to url, id to the item_id.
There were only two keys in the array before and I would combine matches this way.
foreach ($searchArray as $row)
{
$combineMatches[ $row['keyword'] ][] = $row['item_id'];
}
result after using json_encode():
"anthropologist":["27","37"],
"biomedical":["34","35"],
"m.s.":["18","19","23"]
What I currently have:
$combineMatches = array();
foreach ($searchArray as $row)
{
$match =
array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id']+= $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array_push($row['item_id'])
]);
}
}
Result:
[7]=> array(3)
{
["keyword"]=> string(8) "theology"
["url"]=> string(8) "theology"
["item_id"]=> NULL
}
[13]=> array(3)
{
["keyword"]=> string(7) "writing"
["url"]=> string(7) "writing"
["item_id"]=> NULL
}
How do I add to the array column of just item_id ? Which I see is a string, but I need as an array.
This gets JSON encoded in the end of the PHP and read by jquery autocomplete.
Thank you for pointing out the string/array issue.
I changed how to add to the third key if there is a match, and if there isn't a match the solution was changing the array_push to just array.
$combineMatches = array();
foreach ($searchArray as $row)
{
$match=array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id'][] = $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array($row['item_id'])
]);
}
}

How select an array in associate array on the basic on some value

I have an array $arrItems['items'] in which 5 more arrays (associate array) and each array contain 5 element (with the keys: f_name, l_name, contact, address, seller_id).
I want to get all those arrays (from $arrItems['items']) in which element of seller_id is 1 like "seller_id"=>"1,2,3" OR "seller_id"=>"3,2,1" OR "seller_id"=>"4,6,2" OR "seller_id"=>"5,3,4" OR "seller_id"=>"2,1,2" Array given below.
array(5)
{
[0] =>
array(5)
{
["f_name"] =>
string(3) "abc"
["l_name"] =>
string(3) "xyz"
["contact"] =>
string(5) "12345"
["address"] =>
string(3) "xyz"
["seller_id"] =>
string(1) => "1,2,3"
}
[1]=>
array(5) {
["f_name"]=>
string(3) "abc"
["l_name"]=>
string(3) "xyz"
["contact"]=>
string(5) "12345"
["address"]=>
string(3) "xyz"
["seller_id"]=>
string(1)=>"3,2,1"
}
[2]=>
array(5) {
["f_name"]=>
string(3) "abc"
["l_name"]=>
string(3) "xyz"
["contact"]=>
string(5) "12345"
["address"]=>
string(3) "xyz"
["seller_id"]=>
string(1)=>"4,6,2"
}
[3]=>
array(5) {
["f_name"]=>
string(3) "abc"
["l_name"]=>
string(3) "xyz"
["contact"]=>
string(5) "12345"
["address"]=>
string(3) "xyz"
["seller_id"]=>
string(1)=>"5,3,4"
}
[4]=>
array(5) {
["f_name"]=>
string(3) "abc"
["l_name"]=>
string(3) "xyz"
["contact"]=>
string(5) "12345"
["address"]=>
string(3) "xyz"
["seller_id"]=>
string(1)=>"2,1,2"
}
Kindly Help me it actually order table i want to just pick those array in which current seller id is 1 . for example seller No # 1 is login. then all those array select mean those array save in other array.
array_filter (documentation) with in_array (documentation):
$sellerId = "1";
$arr = array_filter($arrItems['items'], function($e) use ($sellerId) {
return in_array($sellerId, explode(",", $e["seller_id"]);
});
If you want only those 5 option use:
$options = array("1,2,3", "3,2,1", "5,3,4", "4,6,2", "2,1,2");
$arr = array_filter($arrItems['items'], function($e) use ($options ) {
return in_array($e["seller_id"], $options);
});
Edited: As for your request this is version of the same code using foreach loop:
$sellerId = "1";
$seller_order_arr = [];
foreach ($arrItems['items'] as $row) {
if (in_array($sellerId, explode(",", $row["seller_id"])))
$seller_order_arr[] = $row;
}
Now $seller_order_arr will hold your filtered array
If I see that correctly, your seller_id value is a concatenated string of Ids. You can filter your outer array with array_filter and a custom callback function, which should return true, if the element should be kept.
$idToLookup = 1;
$filteredItems = array_filter($arrItems['items'], function($element) {
return preg_match('/(^|,)' . $idToLookup . '($|,)/', $element['seller_id']);
]);
Or if you are not so familiar with regex, first explode the number-string into individual numbers and then use in_array:
$idToLookup = 1;
$filteredItems = array_filter($arrItems['items'], function($element) {
$sellerIds = explode(',', $element['seller_id']);
return in_array($idToLookup, $sellerIds);
]);
Use array_filter()
$array = array_filter($arrItems['items'], function ($item) {
$ids = explode(',', $item['seller_id']);
return in_array(1, $ids);
});

How to insert a row of array into another array

Data is coming from 2 differents SQL request, so i have 2 arrays like :
FIRST ARRAY
array(6) {
[0]=>
array(2) {
["edible"]=>
string(3) "600"
["Food"]=>
string(4) "Fruit"
}
[1]=>
array(2) {
["edible"]=>
string(3) "500"
["Food"]=>
string(6) "Vegetables"
}
[2]=>
array(2) {
["edible"]=>
string(4) "1000"
["Food"]=>
string(3) "meat"
}
...
SECOND ARRAY
array(5) {
[0]=>
array(2) {
["out-of-date"]=>
string(3) "17"
["Food"]=>
string(4) "Fruit"
}
[1]=>
array(2) {
["out-of-date"]=>
string(3) "54"
["Food"]=>
string(3) "Vegetables"
}
[2]=>
array(2) {
["out-of-date"]=>
string(2) "60"
["Food"]=>
string(3) "meat"
}
...
What i would like is to merge the two arrays, but not with a function like array_merge or array_merge_recursive.
Because i would like to just add a row (key + value) like
["out-of-date"]=>
string(3) "17""
in the first array if we have the same Food (key)
output result desired :
array(6) {
[0]=>
array(3) {
["out-of-date"]=>
string(3) "17"
["edible"]=>
string(3) "600"
["Food"]=>
string(4) "Fruit"
}
...
You need to make a loop inside loop and verify the food key, if is equal merge the values to another array, Try this code:
<?php
$array1 = array();
$array1[] = array('food' => 'Fruit', 'edible' => '600');
$array1[] = array('food' => 'Vegetables', 'edible' => '500');
$array1[] = array('food' => 'meat', 'edible' => '700');
$array2 = array();
$array2[] = array('food' => 'Fruit', 'out-of-date' => '17');
$array2[] = array('food' => 'Vegetables', 'out-of-date' => '15');
$array_merged = array();
foreach ($array1 as $key => $value) {
$array_merged[$key] = $value;
foreach ($array2 as $ke => $val) {
if ($val['food'] == $value['food']) {
$array_merged[$key]['out-of-date'] = $val['out-of-date'];
}
}
}
print_r($array_merged);
I'm not sure about structure of your database table. But let's you have two tables in your MySql database:
First - edible | Food
Second - out_of_date | Food
So you can query your array by using join mysql operation. You need sql like below:
SELECT *
FROM First
LEFT JOIN Second ON First.Food=Second.Food
Also, you can use additional conditions for all tables like:
SELECT *
FROM First
LEFT JOIN Second ON First.Food=Second.Food
WHERE First.edible = 1000 AND Second.out_of_date = 10
You can find more information here: http://dev.mysql.com/doc/refman/5.7/en/join.html

How to add key name in nested arrays?

I have the following array:
array(5) {
[0]=> array(3) {
[0]=> string(10) "2013-09-18"
[1]=> string(75) "Ready For Retina HD: Create Pixel-Perfect Assets For Multiple Scale Factors"
[2]=> string(74) "ready-for-retina-hd-create-pixel-perfect-assets-for-multiple-scale-factors"
}
[1]=> array(3) {
[0]=> string(10) "2010-10-20"
[1]=> string(40) "Taking A Closer Look At Tech Conferences"
[2]=> string(40) "taking-a-closer-look-at-tech-conferences"
}
[2]=> array(3) {
[0]=> string(10) "2014-10-19"
[1]=> string(29) "Wayfinding For The Mobile Web"
[2]=> string(29) "wayfinding-for-the-mobile-web"
}
[3]=> array(3) {
[0]=> string(10) "2014-05-15"
[1]=> string(24) "Freebie: Icons Of Autumn"
[2]=> string(23) "freebie-icons-of-autumn"
}
[4]=> &array(1){
[0]=> string(0) ""
}
}
How would I go about assigning key names to each part of the inner array? E,g date, title, pathname.
I understand you can do something like this to create an array with certain keys, but how does this work with multiple nested arrays? And how can it be assigned after array creation?
$keys = array('Date', 'Title', 'Filepath');
Assuming $array1 is your main array (with 5 values).
foreach($array1 as $a)
{
if (len($a) == 3)
$array2[] = array("Date" => $a[0], "Title" => $a[1], "Filepath" => $a[2]);
}
$array1 = $array2;
Use a foreach.
$new = [];
foreach ($origArray as $inner) {
$new[] = [
"date" => $inner[0],
"title" => $inner[1],
"filepath" => $inner[2]
];
}
$origArray = $new;
This doesn't handle cases where the item does not conform to the "standard" (e.g item 4) but this should get you started.

sort the array and remove part of it afterwards

I have a 2d array called $myarray and I use var_dump($myarray), it gives me the following:
array(4) {
[0]=> array(3) {
[0]=> string(11) "PAY000003RV"
[1]=> string(3) "EUR"
[2] => string(9) "43,543.23"
}
[1]=> array(3) {
[0]=> string(11) "PAY000002PE"
[1]=> string (3) "USD"
[2]=> string(9) "13,432.34"
} [2]=> array(3) {
[0]=> string(11) "PAY000001YB"
[1] => string(3) "GBP"
[2]=> string(8) "3,432.21"
} [3]=> array(3) {
[0]=> string(11) "PAY000004TS"
[1]=> string(3) "CAD"
[2]=> string(8) "2,321.34"
}
}
I want to get the following output:
GBP 3,432.21
USD 13,432.34
EUR 43,543.23
CAD 2,321.34
so I try to use substr($myarray[0][0], 8, 1), substr($myarray[1][0], 8, 1), substr($myarray[2][0], 8, 1), substr($myarray[3][0], 8, 1) to get the value 3,2,1,4 in order to use it to sort the array to the above order and then delete $myarray[0][0], $myarray[1][0], $myarray[2][0], $myarray[3][0] which are the "PAY0000.." elements in every row, but I am not sure how exactly to implement that, any experts could help me with that? any help will be greatly appreciated!
//Extract sort key
$tmp=array();
foreach($myarray as $m) $tmp[$m[0]]=array($m[1],$m[2]);
//Sort array
ksort($tmp);
//Create output
foreach($tmp as $m) echo $m[0].' '.$m[1];
Some comments:
You can sort by PAY00000nXY without extracting n
The code assumes you need the array for more than printing it out, else it might be inefficient
Let's say your array is assigned to variable $foo
$values = array();
foreach ( $foo as $bar ) {
foreach ( $bar as $val ) {
$values[] = $val[1] . ' ' . $val[2];
}
}
Then you will have the array $values with the values you need.

Categories