基于属性值选择对象的对象数组


array of objects selecting object based on attribute value

我目前正在使用Mailchimp API,我有一个已经运行或将要运行的活动列表,我想获得最近运行的活动的链接。我该如何比较属性"send_time"来查找最近的及其属性的父对象?

活动阵列看起来像这样,

{
    "campaigns": [
        {
            "id": 1,
            "type": "regular",
            "status": "save",
            "send_time": ""
        },
        {
            "id": 2,
            "type": "regular",
            "status": "sent",
            "send_time": "2015-11-11T14:42:58+00:00"
        },
        {
            "id": 3,
            "type": "regular",
            "status": "sent",
            "send_time": "2016-01-01T14:42:58+00:00"
        },
        {
            "id": 4,
            "type": "regular",
            "status": "sent",
            "send_time": "2016-06-12T14:42:58+00:00"
        }
    ]
}

所以在上面的数组中,最后一个对象有最近的send_time,我该如何评估它,然后获取那个对象?我有一个半解决方案,但似乎很冗长。

<?php
    //Build an array of send_times
    $dates = [];
    foreach($result['campaigns'] as $campaign) {
        $dates[$campaign['id']] = $campaign['send_time'];
    }
    //Get the most recent date
    $mostRecent = 0;
    foreach($dates as $k => $v) {
        $curDate = strtotime($v);
        if($curDate > $mostRecent) {
           $mostRecent = $curDate
           $currentId = $k;
        }
    }
    //Get the object
    foreach($results['campaigns'] as $campaign) {
         if($campaign['id'] == $currentId) {
             $c = $campaign;
         }
    }
?>

使用array_multisort(),如下所示(单行代码(:-

<?php    
$data = '{
    "campaigns": [
        {
            "id": 1,
            "type": "regular",
            "status": "save",
            "send_time": ""
        },
        {
            "id": 2,
            "type": "regular",
            "status": "sent",
            "send_time": "2015-11-11T14:42:58+00:00"
        },
        {
            "id": 3,
            "type": "regular",
            "status": "sent",
            "send_time": "2016-01-01T14:42:58+00:00"
        },
        {
            "id": 4,
            "type": "regular",
            "status": "sent",
            "send_time": "2016-06-12T14:42:58+00:00"
        }
    ]
}';
$array = json_decode($data,true)['campaigns']; // decode json string to array  
array_multisort($array,SORT_DESC, SORT_STRING); // use of array_multisort
echo "<pre/>";print_r($array); // this will returns you indexed array like 0,1,2... you can again convert it to campaigns array like $final_array['campaigns'] = $array;
?>

输出:-https://eval.in/598349

注意:-

1.如果给定的数据已经在数组中,则无需使用json_decode(),直接在其上使用array_multisort()

https://eval.in/598355

更多参考:-

http://sg2.php.net/manual/en/function.array-multisort.php

<?php
    $dates = [];
    $recent_campaign = null;
    $recent_time = 0;
    foreach($result['campaigns'] as $campaign) {
        $curDate = strtotime($campaign['send_time']);
        if($curDate > $recent_time) {
            $recent_time = $curDate
            $recent_campaign = $campaign;
        }
    }
    //$recent_campaign is the most recent campaign 
?>

你可以试试这种方法。否则,您可以通过send_time(直接解决方案(使用usort

我还没有执行这个代码!

您可以根据该属性对对象进行排序(我建议使用usort,这样您就可以定义自己的排序(,然后获得该数组中的第一个项。

usort($result, function ($campaign1, $campaign2) {
    if ($campaign1['send_time'] == $campaign2['send_time']) {
        return 0;
    }
    return (strtotime($campaign1['send_time']) > strtotime($campaign2['send_time'])) ? -1 : 1;
});
$mostRecentCampaign = $campaign[0];

注意:我还没有运行这个,所以如果比较函数的return排序错误,您可能需要调整它。

如果您只想获取max元素并想使用更少的代码行,请尝试以下操作:

  1. 通过将"发送时间"列映射到epoch时间并获取最大值来获取最大时间
  2. 根据与该最长时间对应的条目筛选数组
  3. 利润

示例:

$dataArray = /* your array */
$maxTime =  max(array_map('strtotime',array_column($dataArray["campaigns"], 'send_time')));
$maxEntry = array_filter($dataArray["campaigns"], function ($arr) use ($maxTime) { return strtotime($arr["send_time"])==$maxTime; });
print_r($maxEntry);

将打印:

Array
(
    [3] => Array
        (
            [id] => 4
            [type] => regular
            [status] => sent
            [send_time] => 2016-06-12T14:42:58+00:00
        )
)

注意这样做的优点是不需要排序。缺点是排序然后获取最后一个元素会更快。然而,在排序时,您会丢失有时需要的原始数组顺序。