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

时间:2016-06-30 09:17:01

标签: php arrays foreach mailchimp

我目前正在使用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;
         }
    }
?>

3 个答案:

答案 0 :(得分:2)

使用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

答案 1 :(得分:0)

您可以按该属性对对象进行排序(我建议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

答案 2 :(得分:0)

如果您只想获取max元素并希望使用更少行代码,请尝试以下方法:

  1. 通过将“发送时间”列映射到纪元时间并获取最大值来获取最长时间
  2. 按照与该最长时间对应的条目过滤数组
  3. 利润
  4. 示例:

    $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
            )
    
    )
    

    注意这样做的好处是它不需要排序。缺点是排序然后获得最后一个元素会更快。但是,通过排序,您将丢失有时需要的原始数组顺序。