0

Yet another PHP question. I've got two arrays: one string-based and the other numeric. The array of strings contains the names of various buildings. The numeric array tracks relevance of the search in relation to the buildings.

Example: I search for "Armory Building" (http://yoursite.com/search.php?building=Armory+Building)

I loop through all 25 buildings and display any containing one or more search terms (Armory and Building).

Armory Hall Armory State Building Armory Dining Hall Building

Obviously, if the search should bring up results based on relevance, the last two should appear FIRST. How do I sort it so that both arrays get re-ordered but maintain the same index, meaning I re-order the results based on relevance (the last 2 would have a "relevance" of 2 and the first result would have a "relevance" of 1).

2
  • 2
    Try array_multisort Commented Jun 20, 2012 at 13:46
  • No, under strict orders NOT to. Sorry guys, I know it's something expected, but you work with what you got. I got it working thanks to all your help, peeps! Commented Jun 20, 2012 at 13:55

1 Answer 1

1

In this case its not easy to do this. If you have 2 arrays, and you sort one of them, you need in the same time sort the other one and if elements has chenge, related elements need to be changed in 2nd array.

Better way is to keep all in one 2 dimensions array and sort it:
https://www.php.net/array_multisort

Also you could write tour own sorting function, here is example:

<?php

$ar1 = array ('1', '2', '3', '4', '5', '6', '7', '8');
$ar2 = array ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');

for ($j=0;$j<count($ar1)-1;$j++) {
    for ($i=$j;$i<count($ar1)-1;$i++) {
        if ($ar1[$i]<$ar1[$i+1]) {
            //  array 1
            $tmp=$ar1[$i];
            $ar1[$i]=$ar1[$i+1];
            $ar1[$i+1]=$tmp;
            //  array 2
            $tmp=$ar2[$i];
            $ar2[$i]=$ar2[$i+1];
            $ar2[$i+1]=$tmp;
        }
    }
}

?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.