1

What: I'm attempting to compare data in two arrays and write a statement based on the comparison,

$sys = array("1"=>'kitchen lights', "2"=>'living lights', "3"=>'living fan');

$input = array('off kitchen lights','on living fan');

Note: The input can come in any order! :-/ any ideas Compare these to allow for me to change the state in a database and write to a change log.

The sys array key is also important here.

Im shooting for a result like the following:

$write = '1:0,2:256';// means off kitchen lights and on living fan

The write is broken into bits like this:

($sys array key number):('256' on or off '0'),(separate next listing...)

Im familiar with array_intersect.

 $wordin = explode(" ", $input);
 $wordsys = explode(" ", $sys);
 $result = array_intersect($wordin, $wordsys);

Im sure I could loop through the array looking for lets say on and replace it with 256 or 0 but im running to issues thinking of how to do the following:

Handle variations like lights versus light...I need them to be equal for this... Preserve the sys array key number

Note: Im not sure of a "easier" method but I will take any feed back!

Thanks, JT

More Info: A user types a string. Im pulling all the detail out of the string and arriving at the input array. The sys is a predefined database that the user set up.

5
  • 1
    This sounds like an XY-problem meta.stackexchange.com/questions/66377/what-is-the-xy-problem - please tell us about X.
    – Halcyon
    Sep 11, 2013 at 15:22
  • Why would you compare strings to track boolean values? why not: $input = array('kitchen_lights' => false, 'living_fan' => true);
    – NDM
    Sep 11, 2013 at 15:25
  • @NDM The input is derived from a user input string... I cant change this ...However I could achieve this but I would arrive at essentially the same problem as this question.
    – tyler
    Sep 11, 2013 at 15:28
  • @FritsvanCampen X- User inputs a string It gets processed and i arrive here with this array.
    – tyler
    Sep 11, 2013 at 15:28
  • 1
    ok, I've added an answer with an example fiddle
    – NDM
    Sep 11, 2013 at 16:00

2 Answers 2

2

To have different triggers for the same thing, you can do something like this (allows you to add more triggers easily). You could also place some regex in the triggers and evaluate them, but you can figure that out yourself ;)

<?php

define('SWITCHED_ON', 256);
define('SWITCHED_OFF', 0);

$sys = array(
    '1' => array(
        'name' => 'Kitchen Lights',
        'triggers' => array(
            'kitchen light',
            'kitchen lights',
        ),
    ),
    '2' => array(
        'name' => 'Living Lights',
        'triggers' => array(
            'living lights',
            'lights in living room',
            'light in living room',
        ),
    ),
    '3' => array(
        'name' => 'Living Fan',
        'triggers' => array(
            'living fan',
            'fan in living room',
        ),
    ),
);

$input = array('off kitchen lights','on living fan');
$output = array();
foreach ( $input as $command ) {

    // split command at first whitespace
    // $command_array = preg_split('%\s+%', $command, 2);
    // update to allow input like $input = array('kitchen off lights','living fan on');
    $split = preg_split('%\s+%', $command);
    $input_switch = false;
    $input_trigger = array();
    foreach ( $split as $part ) {
        if ( $input_switch === false ) {
            switch ( $part ) {
                case 'on': $input_switch = SWITCHED_ON; break;
                case 'off': $input_switch = SWITCHED_OFF; break;
                default: $input_trigger[] = $part; break;
            }
        } else {
            $input_trigger[] = $part;
        }
    }
    if ( $input_switch === false || empty($input_trigger) ) {
            continue;
    }

    $input_trigger = implode(' ', $input_trigger);


    // insert check if command is valid (for example contains only spaces and alphanumerics.. etc..)
    // ...

    foreach ( $sys as $syskey => $conf ) {
        foreach ( $conf['triggers'] as $trigger ) {
            if ( $trigger == $input_trigger ) {
                $output[] = $syskey.':'.$input_switch;
                continue 3; // continue outer foreach
            }
        }
    }

    // if you arrive here, the command was not found in sys

}
$output = implode(',', $output);
echo $output;

PS: The $sys array looks different, but as u say the user sets them up. So there would be no way to check for all cases of "kitchen lights", "kitchen light", and what other stuff the user puts into the array. So they could just fill the array like above, with different triggers for the same thing. I think the ease of use makes up the extra structure of the new $sys. ^^

UPDATE: Updated to allow unordered input. I think the unordered input is kind of hard to deal with, if you can not be sure how many instances of the word "off" or "on" are found in one command. If there are more instances, you won't be able to decide which "on" or "off" is the correct one. There could be a rule.. like "The first instance of "on" or "off" is the one we'll use" or something. The code above will use that rule. So if you input a command like "kitchen off lights on off", it will result in trying to turn OFF the thing that has a trigger "kitchen lights on off". Another possible way is to reject the command if there are more instances of "on"|"off". Or to cut multiple instances of "on"|"off".

3
  • I really like your trigger idea! Thanks for this. I forgot to add that the on and off can come in any order though! :-/ any ideas
    – tyler
    Sep 11, 2013 at 21:14
  • What do you mean with "any order"? Can you give an example?
    – para
    Sep 12, 2013 at 6:41
  • input could be $input = array('kitchen off lights','living fan on');
    – tyler
    Sep 12, 2013 at 13:35
1

Try this:

$values = array();
foreach ($input as $i) {
    $parts = explode(' ', $i);
    // first word: 'on' || 'off'
    $val = array_shift($parts); 
    // attach the remaining words again to form the key
    $key = implode(' ', $parts);
    // get the index of the $key value in $sys array
    // and concat 0 or 156 depending on $val
    $values[] = array_shift(array_keys($sys, $key)).':'.($val == 'on' ? 256: 0);
}
$write = implode(';', $values);

makes use of the second parameter of array_keys to fetch the correct key of the $sys array.

See it in action in this fiddle

edit

For managing different inputs in different formats (without changing the $sys array):

$alts = array(
    'kitchen lights' => array(
        'kitchen lights', 'kitchen lights', 'lights in kitchen', 'light in kitchen'
    ),
    'living fan' => array(
        'living fan', 'living fans', 'fans in living', 'fan in living'
    ),
);
foreach ($input as $i) {
    $i = strtolower($i); // make sure we have all lower caps
    // check if on in in the start or beginning of the input
    $flag = substr($i, 0, 2) === 'on' || strpos($i, strlen($i)-1, 2) === 'on';
    // remove on and off from the string, trim whitespace
    $search = trim(str_replace(array('on', 'off'), '', $i));
    // search for the resulting string in any of the alt arrays
    $foundSysKey = false;
    foreach ($alts as $sysKey => $alt) {
        if (in_array($search, $alt)) {
            $foundSysKey = $sysKey;
            break;
        }
    }
    // did not find it? continue to the next one
    if ($foundSysKey === false) {
        echo 'invalid key: '.$search;
        continue;
    }
    // now you have the info we need and can precede as in the previous example
    $values[] = array_shift(array_keys($sys, $foundSysKey)).':'.($flag ? 256: 0);
}

I tried saving an updated fiddle but the site seems to have some problems... it did work though.

4
  • This is great! One question any idea how to handle lights versus light. I want the strings to "be equal" do the same thing...If i change the input to light instead of lights...an if statement to look for it and chanage it?
    – tyler
    Sep 11, 2013 at 16:40
  • I forgot to add that the on and off can come in any order though! :-/ any ideas
    – tyler
    Sep 11, 2013 at 21:18
  • Ive updated my answer to reflect these additional requirement, the on/off part can now come at the end or beginning of the input string, and you can add alts for every object.
    – NDM
    Sep 12, 2013 at 7:40
  • I love your coding style! If you have a chance please look at my other question. You nailed this one and id love to see what you think of this question. This is a continuation of that question. stackoverflow.com/questions/18690083/parse-natural-language
    – tyler
    Sep 12, 2013 at 21:59

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.