根据日期同样弹出数组键 [英] Equally popping array keys based on dates

查看:50
本文介绍了根据日期同样弹出数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数组:

I have an array that looks like this:

[numbers] => Array
    (
        [2017-05-14] => 319594
        [2017-05-15] => 319774
        [2017-05-16] => 319962
        [2017-05-17] => 320135
        [2017-05-18] => 320304
        [2017-05-19] => 320459
        [2017-05-20] => 320590
        [2017-05-21] => 320752
        [2017-05-22] => 320882
        [2017-05-23] => 320991
        [2017-05-24] => 321093
        [2017-05-25] => 321144
        [2017-05-26] => 323124
        [2017-05-27] => 324534
        [2017-05-28] => 325123
        [2017-05-29] => 326453
    )

每天都会收集数据,并使用ChartJS将其显示在折线图上.恐怕一两个月之后,约会太多了.

The data gets collected every day and will be shown on a line chart using ChartJS. I'm afraid that after a month or two there's too many dates.

说我想在开始日期和结束日期之间只保留6个键.如何在第一个日期和最后一个日期之间平均弹出键?这必须与任何大小的数组一起使用.

Say I want to keep only 6 keys between start and end date. How can I pop the keys equally between the first and last date? This would have to work with arrays of any size.

我必须保存第一个和最后一个密钥.

I have to save the first and last key.

这是我想出的.这是正确的方法吗?

This is what I came up with. Is this the right way?

$items = Array(
    "2017-05-14" => 319594,
    "2017-05-15" => 319774,
    "2017-05-16" => 319962,
    "2017-05-17" => 320135,
    "2017-05-18" => 320304,
    "2017-05-19" => 320459,
    "2017-05-20" => 320590,
    "2017-05-21" => 320752,
    "2017-05-22" => 320882,
    "2017-05-23" => 320991,
    "2017-05-24" => 321093,
    "2017-05-25" => 321144,
    "2017-05-26" => 323124,
    "2017-05-27" => 324534,
    "2017-05-28" => 325123
);

$desiredSize = 8 ;
$desiredSize--;

$arrayCount = count($items) - 1;
$factor = $arrayCount / $desiredSize;

echo 0 ."\n";
for ( $i = 1; $i <= $desiredSize; $i++ ) {
    echo floor( $i * $factor ) ."\n";
}

推荐答案

您可以结合使用 array_slice array_keys array_search 函数假设您要从键 2017-05-18 2017-05-25 获取数组的切片.代码如下:

You can use a combination of array_slice, array_keys and array_search functions Lets say you want to get slice of array from key 2017-05-18 to 2017-05-25. The code would look like this:

$arrayKeys = array_keys($array);
$firstElementIndex = array_search('2017-05-18', $arrayKeys);
$lastElementIndex = array_search('2017-05-25', $arrayKeys);
$sliceLenght = $lastElementIndex - $firstElementIndex + 1;
$result = array_slice($array, $firstElementIndex, $sliceLenght, true);

其中 $ array 是您的日期数组

这篇关于根据日期同样弹出数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆