1

I have been trying to get this to work for a while now!

What I am trying to do is sort two arrays, so they both get ordered depending on the values inside one of the arrays. I don't know how to "attach" the arrays so both get ordered.

Here is my code:

$html = file_get_html('http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=hat&x=0&y=0');
$test = strtolower("Beechfield Turn-up Beanie");

$arrayT = array();
$arrayP = array();

foreach ($html->find('div.product') as $results) {
    foreach ($results->find('a.title') as $title) {
        $titleLow = strtolower($title->plaintext);
        similar_text($test, $titleLow, $percent);
        $arrayT[] = $title->plaintext;
        $arrayP[] = round($percent);
    }

}

I am comparing how similar the titles brought back from the outside website are to the variable $test, which in this case is just an example.

Next I want my output to be sorted depending on the $percent variables. For example with no sorting the output would be:

title-1 55

title-2 90

title-3 66

However I want it to be sorted:

title-2 90

title-3 66

title-1 55

I have tried using array_multisort however it would only sort each array independently. I have had a look at usort and ksort as well but couldn't get a working answer.

Any help would be appreciated! I have never used any kind of sorting in PHP and have only started learning arrays so please go easy on me.

1 Answer 1

1

I would suggest you to do this: Instead of storing title and percentage in two different array.

you can have array indices as the titles.

Like this:

$html = file_get_html('http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=hat&x=0&y=0');
$test = strtolower("Beechfield Turn-up Beanie");

$arrayTP = array();


foreach ($html->find('div.product') as $results) {
    foreach ($results->find('a.title') as $title) {
        $titleLow = strtolower($title->plaintext);
        similar_text($one, $titleLow, $percent);
        $arrayTP[$title->plaintext] = round($percent);
    }

}

You can sort it later using an array sort function based on the percentage. Use this: asort. Because:

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

For printing do this:

foreach($arrayTP as $title => $percent ) {
.
.
.
1
  • Fantastic that works great! I've been at it all day so thank you very much. Feb 7, 2012 at 21:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.