• Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 85
  • Last Modified:

How to sort array based on how another array was sorted? (php)

I have four php arrays: two with integers ordered from lowest to highest order and two that have strings that correspond to the integers (ie. jack is equal to the fourth position of an integer array, which is seven). So "Jack" must always be in the same position in the array as the number seven (string dependent on integer). Now I have these two of these two arrays for a total of four arrays and I need to combine the two integer arrays into a single array, sort that from lowest to highest, and then have each integer's position correspond to the same string value's position (ie. let's say the ninth position of the integer-combined array is now seven, so Jack must be the ninth position of the string-combined array).
0
Caden Pang
Asked:
Caden Pang
3 Solutions
 
gr8gonzoConsultantCommented:
Is there a reason you don't just use a multidimensional array or an array of objects so that all the data stays together during sorting instead of trying to sort multiple arrays in the same way?

E.g.
Array(
  [0] => array("name" => "Jack", "id" => 7),
  [1] => array("name" => "John", "id" => 12)
)

Then you could just do a usort to sort the array using any of the fields in the child arrays (e.g. sort "id" in ascending order)
1
 
Caden PangHS Sophomore Web DeveloperAuthor Commented:
The values are not predefined so I don't know if Jack will equal 7, 8, 9, etc. Therefore, I need a way for the array positions to correspond. So a multidimensional array solves part of the problem, but not all of it...
0
 
gr8gonzoConsultantCommented:
How are they defined?
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
Caden PangHS Sophomore Web DeveloperAuthor Commented:
They are results scraped from a website, the string is a link, the integer is a price. And they are pulled top to bottom, so the price is not in sequential order...
0
 
NerdsOfTechTechnology ScientistCommented:
In a particular way, I would merge the numerical arrays before sorting them using [ ]; same goes for the string array.

$num1 represents the first numeric array, while $num2 the second.
$str1 represents the first string array, while $str2 the second
the key index of num1&num2 / str1&str2 coresponds to each other, before sort
after sorting, maintaining key link is required

foreach($num2 as $v){
 $num1[]=$v; //push onto num1 with index max(num1+1)
}
foreach($str2 as $v){
 $str1[]=$v; //push onto str1 with index max(str1+1)
}

//maintain key link, use asort()
asort($num1);
asort($str1);

Open in new window


http://php.net/manual/en/function.asort.php
0
 
Julian HansenCommented:
Will there be overlap in the numbers?

Lets say you have array pairs
A1:B1 (A1 is an array of integers, B1 is an array of strings corresponding to those integers)
A2:B2 (as above)

Is it possible for A1 and A2 to contain the same integer?

If not then I would create a new array with the integer value as the key and the string as the value and then just sort it.
0
 
gr8gonzoConsultantCommented:
If they're in a consistent/predictable order at the beginning, you can set up your multi-dimensional array with your values and THEN do the sorting.

So for example, let's say $prices is your numeric array and $links is your string array and the indexes all line up at the beginning. You could do:

$merged = array();
foreach($prices as $index => $price)
{
  $merged[] = array("price" => $price, "link" => $links[$index]);
}

Now $merged should have the data in a neatly-organized multi-dimensional array and you can sort it from there.

Here's a full example showing some basic sample data, the merging process (and the sample output), the sorting code, and then the sample output after the merging and sorting:

<?php
// Some sample data
$prices = array(12.99,354.11,100.99,7.95);
$links = array("linkA","linkB","linkC","linkD");

// Merge into a multi-dimensional array
$merged = array();
foreach($prices as $index => $price)
{
  $merged[] = array("price" => $price, "link" => $links[$index]);
}

// Show what the merged array now looks like (unsorted)
print_r($merged);

/*
OUTPUT:
Array
(
    [0] => Array
        (
            [price] => 12.99
            [link] => linkA
        )

    [1] => Array
        (
            [price] => 354.11
            [link] => linkB
        )

    [2] => Array
        (
            [price] => 100.99
            [link] => linkC
        )

    [3] => Array
        (
            [price] => 7.95
            [link] => linkD
        )

)
*/


// Define our sorting function
function sortByPrice($entryA,$entryB)
{
  if($entryA["price"] == $entryB["price"]) { return 0; } // Same price, don't re-order
  if($entryA["price"] < $entryB["price"]) { return -1; } // A is less than B, return -1
  return 1; // A is greater than B, return 1
}

// Sort our merged array using our sorting function
usort($merged, "sortByPrice");

// Show the new, sorted and merged results
print_r($merged);

/*
OUTPUT:
Array
(
    [0] => Array
        (
            [price] => 7.95
            [link] => linkD
        )

    [1] => Array
        (
            [price] => 12.99
            [link] => linkA
        )

    [2] => Array
        (
            [price] => 100.99
            [link] => linkC
        )

    [3] => Array
        (
            [price] => 354.11
            [link] => linkB
        )

)
*/

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now