PHP Sort Array based on values in another [duplicate] - php

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
PHP - sort an array based on another array?
Need some help regarding array sorting....
I have two arrays. The main one (where the key is the user id) :
$user[31] = 'Tom'
$user[43] = 'Jane'
and another array with the order they should be displayed (where key is the order and value is the user id) :
$order[1] = 43
$order[2] = 31
How can I apply the ordering to the main array using the ordering one?
Thanks guys!

Use the keys in $order to select the users from $user in the right order:
$orderedUsers = array();
foreach ($order as $key) {
$orderedUsers[] = $user[$key];
}

Use this one, it is usefull for your problem
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
Result as :
Array
(
[0] => XL
[1] => gold
)

Related

PHP array sort with forced the first row [duplicate]

This question already has answers here:
Move array item with certain key to the first position in an array, PHP
(9 answers)
move array element to the first position but remain order
(4 answers)
Move an array element to a new index in PHP
(9 answers)
Move Value in PHP Array to the Beginning of the Array
(12 answers)
Move array element with a particular value to top of array
(2 answers)
Closed 2 months ago.
How to sort an array at PHP to force selected row as a first ?
My array is
array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');
How to sort the array to force
array[]=array(id=>'b', content=>'apple');
as a first row and doesn't matter the rest (apple is the key).
And in other example turn sort to get
array[]=array(id=>'d', content=>'cherry');
as a first row and doesn't matter the rest (cherry is the key).
Another way to do this is to effectively rotate the array using array_slice, bringing the element you want to the start:
$first = 'apple';
$k = array_search($first, array_column($array, 'content'));
$array = array_merge(array_slice($array, $k), array_slice($array, 0, $k));
print_r($array);
Output:
Array (
[0] => Array ( [id] => b [content] => apple )
[1] => Array ( [id] => c [content] => banana )
[2] => Array ( [id] => d [content] => cherry )
[3] => Array ( [id] => a [content] => lemon )
)
Demo on 3v4l.org
There are 2 ways I can think of doing this. The first is as Ultimater in the comments suggest to extract the matching row, then sort and then add the row back in...
$first = 'apple';
$array = [];
$array[]=array('id'=>'a', 'content'=>'lemon');
$array[]=array('id'=>'b', 'content'=>'apple');
$array[]=array('id'=>'c', 'content'=>'banana');
$array[]=array('id'=>'d', 'content'=>'chery');
$firstElement = array_search($first, array_column($array, "content"));
$row = $array[$firstElement];
unset($array[$firstElement]);
sort($array);
array_unshift($array, $row);
print_r($array);
The second is to use usort and add specific clauses in that if the key matches the row you want first, then it will always force it to the first row...
$first = 'apple';
usort($array, function ($a, $b) use ($first){
if ( $a['content'] == $first) {
return -1;
}
if ( $b['content'] == $first) {
return 1;
}
return $a <=> $b;
});
print_r($array);
(I've used <=> in this which is PHP 7+, there are alternatives if you need to use PHP 5).
If as your comment suggests that there is no need to sort the rest of the data, then the first set of code minus the sort() should do.
One other option - if id:content is one to one, we can index the array by content and merge with an array with a single empty "apple" key (or whichever content value you're looking for).
$array = array_merge(['apple' => []], array_column($array, null, 'content'));
If the resulting string keys are undesirable the array can be reindexed with array_values.
If the array only contains id and content and id:content is in fact one to one, a "dictionary" of key-value pairs will be handier to deal with than a list of rows like this and it would probably be better to set the array up that way to begin with if possible.
If id:content is not one to one, then... never mind. ;-)

How to calculate difference between keys and values in php [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have two types of arrays:
1:
$array1["a"][] = "value1";
$array1["a"][] = "value2";
$array1["b"][] = "value3";
2:
$array2["0"] = "a";
What I need now is to somehow find difference between these two arrays. I need to filter out array1 by key, which is located in array2 value. I have tried doing the following:
array_diff(array_keys($array1), array_values($array2));
But I get the following error on that line:
ErrorException Array to string conversion
Any ideas?
Something like this?
foreach ($array1 as $key => $value)
if( array_search ($key , $array2 ))
unset($array1[$key]);
If $array1 needs to have the values, you just need to put the diff in $array1 :
$array1 = array_diff(array_keys($array1), array_values($array2));
Depending on how you constructed your arrays, it should work. The following code (based on your question) worked:
<?php
$array1=array("a" => array(),"a" => array(),"b" => array());
$array2=array("0"=>"a");
print_r(array_keys($array1));
echo("<br/>");
print_r(array_values($array2));
echo("<br/>");
print_r(array_diff(array_keys($array1), array_values($array2)));
>
This results in:
Array ( [0] => a [1] => b )
Array ( [0] => a )
Array ( [1] => b )

get the first sub array key with out looping a multidimensional array PHP [duplicate]

This question already has answers here:
Get first key in a (possibly) associative array?
(25 answers)
Closed 5 years ago.
hi i have a multidimensional l array .
Array
(
[1] => Array
(
[38] => Fashion Retail | Fashion Accessories
)
[10] => Array
(
[194] => Automotive | 4x4
[206] => Automotive | Aftermarket Parts and Kits
[201] => Automotive | ATVs
)
)
i want to get the first sub array's key , in this scenario it is 1 , i can get it using a foreach loop .
foreach($myarry as $key=>$val)
is there any way to achieve this with out looping , please help . thanks in advance
If using >= PHP 5.5...
$first = array_keys($myarry)[0];
If using an older PHP, just assign the keys somewhere, and then subscript the first element as normal.
$arrKeys = array_keys($array);
$key = array_shift($arrKeys); // gives first key
Returns the first key and deletes this from the arrKeys, hence the next key, 10 in this case will be returned on next call. No need to make another array.
yep, I did that , I have used
current(array_keys($my_array))
print_r($myarry[array_keys($myarry)[0]]);
Please try:
reset($myarry);
$first_key = key($myarry);

Check arrays to find common data [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Find common values in multiple arrays with PHP
I'm trying to find the number of friends two users have in common. Each users friends user id's are stored in the data base like this: 12, 13, 14. This is my code.
$my_friends = explode(',', $my_friends);
print_r($my_friends);
This outputs: Array ( [0] => 12 [1] => 13 [2] => 14 )
These are my friends user id's. Now for the next user:
$users_friends = explode(',', $users_friends);
print_r($users_friends);
This outputs: Array ( [0] => 12 )
How do I show that user 1 and user 2 have id 12 in common ?
Besides suggesting that you should normalise your database, which would make this easy to do with a simple SQL Query:
Explode the $myFrieds and $users_friends arrays, then use the array_intersect() function to find the common entries, and count() those
You could use array_intersect().
print_r(array_intersect($my_friends, $users_friends));
will output Array ( [0] => 12 )
You can use array_intersect:
$common_friends = array_intersect($my_friends, $users_friends);

How to add a new [key] => [value] pair after a specific Associative Key in an Assoc Array in PHP? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
array_splice() for associative arrays
How to add an array value to the middle of an associative array?
How can I add a new [key] => [value] pair after a specific Associative Key in an Assoc Array in PHP ?
For example, let's say we have an array called $fruits:
array {
[apple] => 1
[banana] => 3
[orange] => 4
}
How can I add [plum] => 2 to $fruits so that it appears after the [apple] key but before [banana] key ?
Thanks.
You'll probably need to use array_splice() to cut the array into two pieces, and then recreate the array with array_merge() - Try this nifty function I just whipped up.
Live Sample: http://codepad.org/gGm5C1od
<?php
$orig = array(
"apple" => 1,
"banana" => 3,
"orange" => 4,
);
$orig = InsertKeyValuePair($orig, "plum", 2, 1);
var_dump($orig);
function InsertKeyValuePair($arr, $key, $val, $index){
$arrayEnd = array_splice($arr, $index);
$arrayStart = array_splice($arr, 0, $index);
return (array_merge($arrayStart, array($key=>$val), $arrayEnd ));
}
?>
If your ultimate goal is serial number(or something else) of fruits based on there name
for eg to find serial number of apple you will use fruits['apple'] then it doesn't matter where a particular element in array exists and if you really want to do it your own way then you can use array_splice() function
Here's a nice tutorial
http://www.ferolen.com/blog/insert-into-add-element-to-array-at-specific-position-php/
Assuming associative keyed arrays have a predictable order is not good design. If you want enforced order, you should mandate it in your design. For example key the array by the order number, then write custom functions to retrieve data by fruit name.
If you keep assuming keys have a natural order, one day you will run into a scenario where the order may not be as you expected it, and you will have broken functionality.

Categories