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

时间:2012-02-25 13:25:26

标签: php arrays icloud

我正在使用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
                )

        )

   )

任何有关如何使这项工作得到帮助的帮助将不胜感激。这似乎很容易,但由于某种原因,我无法让它发挥作用。

干杯!

1 个答案:

答案 0 :(得分:1)

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

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;
}

你可以使用数组过滤器实现相同的功能,如果你只需要一个gruop就需要获得所有组array_filter,这会更有效。