简体   繁体   English

根据最近的日期和另一个值返回多维数组值

[英]Return multidimensional array value based on most recent date and another value

I am basing my code on the following link: PHP Multidimensional Array Searching (Find key by specific value) I attempted to add code similar to Get most recent date from an array of dates ; 我将代码建立在以下链接的基础上: PHP多维数组搜索(按特定值查找键)我试图添加类似于从日期数组中获取最新日期的代码; however I kept receiving illegal offset errors. 但是我一直收到非法的补偿错误。

I can successfully select the proper value based on the first code. 我可以根据第一个代码成功选择适当的值。 How can I then narrow down my return based on the most recent date in the array? 然后,如何根据数组中的最新日期来缩小收益范围?

I am using php 5.4.45 and my array is always sorted by date with the most recent being last. 我正在使用php 5.4.45,我的数组总是按日期排序,最近的是最后一个。 I cannot simply select the last array index as it is not always a "Paid" order status. 我不能简单地选择最后一个数组索引,因为它并不总是“已付费”订单状态。

My Array: 我的阵列:

array(4) { 
[0]=> array(3) { 
    ["status"]=> string(6) "Active" 
    ["check_number"]=> string(0) "" 
    ["date_added"]=> string(19) "17/11/2015 10:34:53" } 
[1]=> array(3) { 
    ["status"]=> string(4) "Paid" 
    ["check_number"]=> string(5) "12345" 
    ["date_added"]=> string(19) "14/12/2015 07:40:59" } 
[2]=> array(3) { 
    ["status"]=> string(8) "Invoiced" 
    ["check_number"]=> string(0) ""  
    ["date_added"]=> string(19) "14/12/2015 09:44:31" } 
[3]=> array(3) { 
    ["status"]=> string(4) "Paid" 
    ["check_number"]=> string(4) "0258" 
    ["date_added"]=> string(19) "14/12/2015 09:53:29" } 
} 

My code: 我的代码:

function getValue($fromSource, $field, $value, $get){
    if ($fromSource[$field] === $value) {
        return $fromSource[$get];
    };
    return false;
}
foreach ($order['order_history'] as $order_history) {
    var_dump(getValue($order_history, "status", "Paid", "check_number"));
}

Desired result: "0258" (where status = "Paid" and date = most recent) 所需结果:“ 0258”(状态=“已付费”,日期=最近)

Currently Receiving: "12345" "0258" (where status = "Paid") 当前接收:“ 12345”“ 0258”(状态=“已付费”)

If the array is always sorted, you can use this code to get the newest entry matching the corresponding status: 如果始终对数组进行排序,则可以使用以下代码获取与相应状态匹配的最新条目:

    function getLatest($arr, $field, $value, $getField){

        for($i=count($arr)-1;$i >= 0; $i--){
                $currSubArr = $arr[$i];
                if($currSubArr[$field] === $value){
                    return $currSubArr[$getField];

                }   

        }
    }
    $orders[] = array('status' => 'active', 'checknumber'=> '121234','date_added' => '17/11/2015 10:34:53');
    $orders[] = array('status' => 'paid', 'checknumber' => '1212334','date_added' => '17/11/2015 10:38:53');
    $orders[] = array('status' => 'paid', 'checknumber '=> '5234','date_added' => '17/11/2015 10:42:53');



  //test --> returns 5234 
    echo getLatest($orders,'status','paid','checknumber');

Using array_walk we collect all the dates. 使用array_walk我们收集所有日期。

We transform the dates into timestamps, using createFromFormat and getTimestamp , so we can easily order them, not forgetting to pass a timezone . 我们使用createFromFormatgetTimestamp将日期转换为时间戳,因此我们可以轻松地对它们进行排序,而不会忘记传递timezone

We get the key of the highest timestamp, and use it to access the list of items. 我们获得了最高时间戳的密钥,并使用它来访问项目列表。

$items being the initial array. $items是初始数组。

$dates = array();

$format = 'd/m/Y H:i:s';
$timezone = new DateTimeZone('UTC'); 

array_walk($items,function($item,$index) use(&$dates,$format,$timezone){
    $date = DateTime::createFromFormat($format, $item["date_added"],$timezone);
    $dates[$index] = $date->getTimestamp();
});

// get the key of the most recent date
$key = array_keys($dates, max($dates))[0];

// using the key get the item from the list
print_r($items[$key]) . PHP_EOL;

Will output 将输出

Array
(
    [status] => Paid
    [check_number] => 0258
    [date_added] => 14/12/2015 09:53:29
)

From here you can easily access only one element of the result 从这里您可以轻松访问结果的一个元素

print $items[$key]["check_number"];

Will output 将输出

0258

I think another possibility is to loop your array with a foreach construct and check for every array in the iteration if "status" is "Paid". 我认为另一种可能性是使用foreach构造循环您的数组,并在迭代中检查“状态”是否为“已付费”的每个数组。 Then every iteration you can compare the date from the current $item with the date in the $result array by using a DateTime object. 然后,每次迭代都可以使用DateTime对象将当前$item中的日期与$result数组中的日期进行比较

For example: 例如:

$items = array(
    array(
        "status" => "Active",
        "check_number" => "",
        "date_added" => "17/11/2015 10:34:53"
    ),
    array(
        "status" => "Paid",
        "check_number" => "12345",
        "date_added" => "14/12/2015 07:40:59"
    ),
    array(
        "status" => "Invoiced",
        "check_number" => "",
        "date_added" => "14/12/2015 09:44:31"
    ),
    array(
        "status" => "Paid",
        "check_number" => "0258",
        "date_added" => "14/12/2015 09:53:29"
    )
);

$result = array();

foreach ($items as $item) {
    if ($item["status"] === "Paid") {

        // If there is no result yet with status "Paid", then add it.
        if (count($result) === 0) {
            $result = $item;
            continue;
        }

        $itemDateTime = DateTime::createFromFormat('d/m/Y H:i:s', $item["date_added"]);
        $resultDateTime = DateTime::createFromFormat('d/m/Y H:i:s', $result["date_added"]);

        if ($itemDateTime > $resultDateTime) {
            $result = $item;
        }
    }
}

var_dump($result);

Will result in: 将导致:

array (size=3)
  'status' => string 'Paid' (length=4)
  'check_number' => string '0258' (length=4)
  'date_added' => string '14/12/2015 09:53:29' (length=19)

Then you can access your value from the $result array like this: 然后,您可以从$result数组访问您的值,如下所示:

echo $result["check_number"];

Will result in: 将导致:

0258 0258

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM