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).
Caden PangHS Junior Web DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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 Junior 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
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

Caden PangHS Junior 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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
arrays

From novice to tech pro — start learning today.