PHP数组-根据设置的参数选择对象


PHP Array - Select object based on set parameters

我正在使用php脚本来跟踪我的iPhone在项目中的位置。我正在使用的脚本可以在github上找到。然而,我面临的问题是,它正在跟踪设备。我的笔记本电脑和iPhone。我希望它只跟踪iPhone,但如果需要,我希望能够在两个设备之间轻松切换;换句话说,我希望优先追踪iPhone,然后是笔记本电脑。因此,我正在考虑使用"deviceClass"来确定要选择的设备,但我不知道如何将其添加到文件中:class.sosumi.php这里是数组输出:

    Sosumi Object
(
    [devices] => Array
        (
            [0] => SosumiDevice Object
                (
                    [isLocating] => 1
                    [locationTimestamp] => **
                    [locationType] => Wifi
                    [horizontalAccuracy] => 65
                    [locationFinished] => 1
                    [longitude] => **
                    [latitude] => **
                    [deviceModel] => MacBookPro7_1
                    [deviceStatus] => 200
                    [id] => **
                    [name] => **
                    [deviceClass] => MacBookPro
                    [chargingStatus] => 
                    [batteryLevel] => 0
                )
            [1] => SosumiDevice Object
                (
                    [isLocating] => 1
                    [locationTimestamp] => **
                    [locationType] => Wifi
                    [horizontalAccuracy] => 65
                    [locationFinished] => 1
                    [longitude] => **
                    [latitude] => **
                    [deviceModel] => FourthGen
                    [deviceStatus] => 203
                    [id] => **
                    [name] => **
                    [deviceClass] => iPhone
                    [chargingStatus] => NotCharging
                    [batteryLevel] => 0.5866984
                )
        )
   )

如有任何帮助,我们将不胜感激。这看起来很容易,但由于某种原因,我无法使它发挥作用。

干杯!

我不确定我是否清楚地回答了你的问题,但你需要:

array_filter

这将允许你像这样过滤你的阵列:

// Reference is implicit (I've added & for you to see it)!!!
// Be careful not to change your data
functon filterCallback( SosumiDevice &$obj){ 
    return $obj->deviceClass == 'MacBookPro';
}

usort

排序第一个是MacBooks 的数组

function usortCallback( SosumiDevice $a, SosumiDevice $b){
    static $order = array(
         'MacBookPro' => 1,
         'FourthGen' => 2,
         ...
    );
    $oA = isset( $order[ $a->deviceClass]) ? $order[ $a->deviceClass] : -100;
    $oB = isset( $order[ $b->deviceClass]) ? $order[ $b->deviceClass] : -100;
    // Maybe reverse order of operands will be necessary
    return $oA - $oB;
}

这样添加的值类如下:

  • MacBookPro => 1
  • FourGen => 2

因此,当您添加参数时,如:MacBookPro, FourthGen

计算为:1 - 2,返回-1=>MacBookPro应在FourthGen 之前

foreach回路

根据设备类型将设备拆分为组:

$groups = array();
foreach( $this->devices as $device){
    if( !isset( $groups[ $device->deviceType])){
        $groups[ $device->deviceType] = array( $device);
        continue;
    }
    $groups[ $device->deviceType] = $device;
}

你可以用数组过滤器实现同样的效果,如果你需要得到所有的组,array_filter,当你只需要一个groop时,这会更有效。