I have a special problem over in terms of sorting out those words like a keyboard type.
For example:
the user inputs these words into the textarea

HOUSE
DOLL
KITE
NICE

Then, the result should be
DOLL
HOUSE
KITE
NICE

this is sorted out according to the qwerty order.

<?php 
$words = array();
        $order=array('q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m');
$qwerty_words = array();
            if(isset($_POST['submit'])){
                $text = $_POST['texts'];
                $text = "one two free";

                $separate_of_texts = explode(" ",$text);
                //$words = array($separate_of_texts);
                $count_words = count($separate_of_texts);
                $count_order = count($order);
                //storing array values
                for($i= 0; $i<$count_words;$i++){
                        $words[$i]=$separate_of_texts[$i];
                }

                for($i=0;$i<$count_words;$i++){
                    $temp = array();
                    $sep_letters=explode(' ',$words[$i]);

                    if(!in_array($sep_letters[$i], $order)){

                    }

                }

                foreach($qwerty_words as $values){

                    echo $values.'<br/>';
                }
                echo '<br/>'.$count_words;
            //}


    ?>

The code above is mine and I don't know what kind of algo will use for this kind of problem

Recommended Answers

All 10 Replies

You can use usort to sort the array of words, using your own comparison function. The comparison function should return a negative value if the first word comes before the second word. Basically, you can check the first letters. If they are equal, check the next (and so on). If you subtract the index of the second letter in your qwerty array, from the index of the first, you'll have your comparison.

by the way, I've already updated my codes:

<?php

    $words = array("one,two,free");
    $order = array('q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m');
    $key = array();
                    $text = "one two free";

                    $words = explode(" ",$text);

                    for($i=0;$i<count($words);$i++){

                        $next_word = $words[$i];
                        $fletter_nextword = get_first_letter($next_word);
                        $key_nextword =get_key($fletter_nextword,$order);

                        $key[$i] = $key_nextword;

                    }

                    $words_key = array_combine($key, $words);
                    ksort($words_key);

                    foreach ($words_key as $key => $value){

                        echo $value.'</br>';
                    }

    function get_first_letter($this_word){

        $temp = explode(' ',$this_word);
        return $temp[0];
        }

    function get_key($the_word,$order){
        $key="";
        $i=0;

        do{
            if($the_word==$order[$i]){
                $flag = "TRUE";
                $key = $i;
            }
            else{
                $flag = "FALSE";
            }

            $i++;
        }while($flag=="FALSE");


        return $key;
    }

?>

my problem is, it says. undefined offset.
this is simply sort the words by comparing the first letter.

it says. undefined offset.

What line ?

Member Avatar for diafol

Maybe like this? Off top of head - tested - seems oK:

function myUsort($words,$sortarray=false){

    if(!$sortarray || !is_array($sortarray)){
        $order=array('q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m');
    }

    $key_order = array_flip($order);

    if(!is_array($words)){
        $words = explode(' ',$words);   
    }

    foreach($words as $word){

        $chars = str_split($word);
        foreach($chars as $char){
            if(isset($key_order[$char])){
                $tot[] =  str_pad($key_order[$char],2,'0', STR_PAD_LEFT);   
            }
        }
        if(isset($tot)){
            $key = implode('.',$tot);
            $num_array[$key] = $word;
            unset($tot);
        }
    }

    if(isset($num_array)){
        ksort($num_array);
        return $num_array;
    }   
}

if($sorted = myUsort('yield foos food'))print_r($sorted);

This would be my solution:

<?php
  function qwertySort($left, $right) {
    $order = array('q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m');

    $lenLeft = strlen($left);
    $lenRight = strlen($right);

    $result = 0;
    for ($i = 0; $i < min($lenLeft, $lenRight); $i++) {
      $result = array_search($left[$i], $order) - array_search($right[$i], $order);
      if ($result != 0) break;
    }

    if ($result == 0)
      $result = $lenLeft - $lenRight;

    return $result;
  }

  $words = array ('foos',  'foo', 'yield', 'quux');
  usort($words, 'qwertySort');
  print_r($words);
?>

In addition to your PM, read about it in the manual. If this still doesn't explain it all, post a new reply.

I already read the manual. Still, I don't know what's the data that's being passed

<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

in usort ($a,"cmp")

to function cmp ($a,$b)

why does the function cmp is between --> ""
in the argument usort($a,"cmp") ?

Member Avatar for diafol

Seems this is solved? If so, nevermind. Pritaeas shows how it should be done with usort.
My effort is a bit of a mongrel, but I tinkered a bit with it, so I'll include it for completeness' sake:

function myUsort($words,$sortarray=false){
    if(!$sortarray || !is_array($sortarray))$sortarray=array('q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m');
    $key_order = array_flip($sortarray);
    if(!is_array($words))$words = explode(' ',$words);
    foreach($words as $word){
        $chars = str_split(strtolower($word));
        $tot = '';
        foreach($chars as $char) $tot .=  (isset($key_order[$char])) ? str_pad($key_order[$char],2,'0', STR_PAD_LEFT) : '';
        if($tot != '')$num_array[$tot] = $word;
    }
    if(isset($num_array)){
        ksort($num_array, SORT_STRING);
        return array_values($num_array);
    }   
}

$sentence = "how will this pan out under qwerty";
$words = array("how","will","this","pan","out","under","qwerty");
$myorder = range("a","z");

//sentence with default qwerty
if($sorted = myUsort($sentence))print_r($sorted);
//words with default qwerty
if($sorted = myUsort($words))print_r($sorted);
//sentence with custom order (A-Z)
if($sorted = myUsort($sentence, $myorder))print_r($sorted);
//words with custom order (A-Z)
if($sorted = myUsort($words, $myorder))print_r($sorted);

Thanks for the elaboration diafol =)

why does the function cmp is between --> ""
in the argument usort($a,"cmp") ?

"cmp" is the name of the function being called as a string. Internally it is most likely an 'eval' kind of code. $a and $b are the parameters to that function. Basically it is called several times while performing a sort. Each pass compares two values in the array. If you echo them both in the cmp function, you can see for yourself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.