In my PHP file I have 2 arrays, in each one the keys are numbered from 0 to its last index, and they both contains the same array elements number, as they are containing data on the same contact, but each array contains a different data about the same contact, and each contact has an ID which is his index on the array.
I have sorted the first array descending according to the values, so the keys are in different sort, and the values are descending. I want to sort the second array, in the same way, so they would have the same keys order, and then to do array_values on both of the arrays, in order it to have new ascending keys order.
For example I have these 2 arrays:
$arr1 = array('0' => 'John', '1' => 'George', '2' => 'James', '3' => 'Harry');
$arr2 = array('0' => '12', '1' => '8', '2' => '34', '3' => '23');
I have sorted $arr2 descending according to his values like this:
arsort($arr2);
// So now, $arr2 is "[2] => '34', [3] => '23', [0] => '12', [1] => '8'"
I want to sort $arr1 in the same way so it will also be:
$arr1 = array('2' => '34', [3] => '23', [0] => '12', [1] => '8');
How can I do this so the arrays will be sorted in the same keys order?
How about this? Using array_replace():
<?php
$arr1 = array('0' => 'John', '1' => 'George', '2' => 'James', '3' => 'Harry');
$arr2 = array('0' => '12', '1' => '8', '2' => '34', '3' => '23');
arsort($arr2);
var_dump(array_replace($arr2, $arr1)); // array(4) { [2]=> string(5) "James" [3]=> string(5) "Harry" [0]=> string(4) "John" [1]=> string(6) "George" }
Demo
How about using array_multi_sort()? It rearranges all arrays to match the order of the first sorted array.
// as elements of $arr2 are shifted, corresponding elements of $arr1 will have the same shift
array_multisort($arr2, SORT_DESC, $arr1);
Live demo
So you have two arrays, so why not just loop over the second array and use its as a key order to create a new array using the the values from the 1st array..
$newArray = array();
foreach (array_keys($arr2) as $key) {
$newArray[$key] = $arr1[$key];
}
// then apply sorting to new array
arsort($newArray);
Then simply print your new array $newArray to check your result.
print_r($newArray) or var_dump($newArray)
Expected output will be:
array(4) {
[0]=>
string(4) "John"
[2]=>
string(5) "James"
[3]=>
string(5) "Harry"
[1]=>
string(6) "George"
}
Similarly if you want an opposite, Then change just replace $arr2 with $arr1 like wise.
$newArray = array();
foreach (array_keys($arr1) as $key) {
$newArray[$key] = $arr2[$key];
}
// then apply sorting to new array
arsort($newArray);
var_dump($newArray)`
Expected output will be:
array(4) {
[2]=>
string(2) "34"
[3]=>
string(2) "23"
[0]=>
string(2) "12"
[1]=>
string(1) "8"
}
Related
I have this array:
$array = array(
['name' => 'Indor Swimming Pool'],
['name' => 'abracadabra'],
);
I want sort if alphabetically, so I did:
usort($array, function($a, $b)
{
return strcmp($a['name'], $b['name']);
});
but when I dump it:
var_dump($array);
I get:
array(2) {
[0]=>
array(1) {
["name"]=>
string(19) "Indor Swimming Pool"
}
[1]=>
array(1) {
["name"]=>
string(11) "abracadabra"
}
}
this is incorrect, abracadabra should go as first
According to the ASCII table chr I comes first and then comes the a chr
ASCII Table
So here your array is actually getting sorted alphabetically to achieve the desired result you need to sort the array in the descending order
<?php
$data = array(
['name' => 'Indor Swimming Pool'],
['name' => 'abracadabra'],
);
arsort($data);
?>
Output
Array
(
[1] => Array
(
[name] => abracadabra
)
[0] => Array
(
[name] => Indor Swimming Pool
)
)
It works as intended. The reason for this order is that 'a' is actually after 'I' in ASCII.
I have array in this structure, and I want delete item[6] from array.
I used unset($arrayname[6]) in php but it's not working. Any help? Is there any way I can remove element [6] from array?
array(2) {
[6]=>
array(2) {
["id"]=>
string(1) "1"
["day"]=>
string(6) "Monday"
}
[7]=>
array(2) {
["id"]=>
string(1) "2"
["day"]=>
string(7) "Tuesday"
}}
This works as you would expect:
<?php
$days =
array (
6 =>
array (
'id' => 1,
'day' => 'Mon',
),
7 =>
array (
'id' => 2,
'day' => 'Tue',
)
);
unset($days[6]);
var_export($days);
Output:
array (
7 =>
array (
'id' => 2,
'day' => 'Tue',
),
)
You can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically.
$array2 = {{array of array}}
// remove item at index 6 which is 'for'
unset($array2[6]);
// Print modified array
var_dump($array2);
// Re-index the array elements
$arr2 = array_values($array2);
//Print re-indexed array
var_dump($array2);
This solution will work, please check and let me know.
I promise you I've had a look at the many existing SO Qs about PHP sorting, including this mega one
I've got a PHP associative array, with strings as keys. Each value is an array of integers. I want to sort each array of integers, in simple ascending numerical order. I'm convinced this should be easy, and I've found enough examples that I think I should be doing the right thing, but it's not quite working, so there's a typo or I'm an idiot or something...
PHP:
//Each fruit corresponds to an array (series) of integers
$data = [
'banana' => [
1,3,2
],
'orange' => [
5,1,3
]
];
echo "Before sort:\n";
var_dump($data);
//For each fruit, I want to order the numbers
foreach ($data as $key => $series)
{
//Sort array of integers
sort($series);
//NB I wasn't sure about value/reference details of foreach loops, so I also tried
//retrieving a series into a variable, sorting, and then reassigning back to the same key
}
echo "\n\nAfter sort:\n";
var_dump($data);
Output:
Before sort:
array(2) {
'banana' =>
array(3) {
[0] =>
int(1)
[1] =>
int(3)
[2] =>
int(2)
}
'orange' =>
array(3) {
[0] =>
int(5)
[1] =>
int(1)
[2] =>
int(3)
}
}
After sort:
array(2) {
'banana' =>
array(3) {
[0] =>
int(1)
[1] =>
int(3)
[2] =>
int(2)
}
'orange' =>
array(3) {
[0] =>
int(5)
[1] =>
int(1)
[2] =>
int(3)
}
}
As you can see, in the output the inner arrays of integers have not been sorted. What am I doing wrong? (PHP 5.5.9, Windows 7)
Use a reference &:
foreach ($data as $key => &$series)
{
//Sort array of integers
sort($series);
// OR
// sort($data[$key]);
}
I have two arrays like this
$array1 = ['name'=>'john', 'age'=> 10]
$array2 = ['name' => 'johnKaff', 'class' => 'User', 'option'=array('c1', 'c2')]
The result i want is
$array2 = ['name' => 'john', 'class' => 'User', 'option'=array('c1', 'c2'), 'age'=> 10]
The values from $array1 should always override if have same key in $array2
Use array_replace():
$result = array_replace($array2, $array1);
Where:
$array1 - The array in which elements are replaced.
$array2 - The array from which elements will be extracted.
Output:
Array
(
[name] => john
[class] => User
[option] => Array
(
[0] => c1
[1] => c2
)
[age] => 10
)
Use the + operator:
$combined_array = $array1 + $array2;
The array listed first wins when each array has an element with the same key.
Example:
$array1 = array('name'=>'john', 'age'=> 10);
$array2 = array('name' => 'johnKaff', 'class' => 'User', 'option'=>array('c1', 'c2'));
$combined_array = $array1 + $array2;
var_dump($combined_array);
Output:
array(4) {
["name"]=>
string(4) "john"
["age"]=>
int(10)
["class"]=>
string(4) "User"
["option"]=>
array(2) {
[0]=>
string(2) "c1"
[1]=>
string(2) "c2"
}
}
You should use array_merge:
array_merge($array1, $array2);
I have an array as follows:
array(1) {
[0]=> string(1) "2"
[1]=> string(1) "1"
[2]=> string(1) "3"
[3]=> string(1) "4"
[4]=> string(1) "5"
[5]=> string(1) "6"
[6]=> string(1) "7"
}
}
What I would like to do is order a second Array based on the above (which alters with user selection):
Array {
"Two" => "Two",
"One" => "One",
"Three" => "Three",
"Four" => "Four",
"Five" => "Five",
"Six" => "Six"
"Seven" => "Seven"
}
EDIT: The user access the page where there is a jQuery Sortable list - they order it as they please and this is saved to the DB, what I'm trying to do now is when the user comes back to the page is make sure the list is in the order they set out. So it is the order they set.
The second array is the array that populate the list on the .PHP page and that's why I need it to match the first array.
I've looked at array_multisort but no joy.
I'm assuming I'd do some of Loop in PHP to populate the second array before using it but I'm struggling - any suggestions?
I guess array_combine is what you are searching for:
$indexes = array('2','1');
$indexes = array_merge($indexes, range(3,7)); // used range to fill missing indexes
$values = array('two', 'one', 'three', 'four', 'five', 'six', 'seven');
$result=array_combine($indexes, $values);
ksort($result); // sort by keys
print_r($result);
// Array
// (
// [1] => one
// [2] => two
// [3] => three
// [4] => four
// [5] => five
// [6] => six
// [7] => seven
// )
I do not fully understand your goal but I think the following code will produce your desired result
$data = array("two", "one", "three", "seven");
$result = array();
foreach ( $data as $item) {
$result[$item] = $item;
}
print_r($result);
This will output
Array
(
[two] => two
[one] => one
[three] => three
[seven] => seven
)