简体   繁体   English

如何从数组键中删除前导零

[英]How to remove leading zeros from array keys

I'm using Codeigniter 3 (calendar class) and I have this function to get calendar data (the table just has a date column and a data column): 我正在使用Codeigniter 3(日历类),我有这个函数来获取日历数据(该表只有一个日期列和一个数据列):

    function get_calendar_data($year, $month) {
    $query = $this->db->select('date, data')->from('calendar')->like('date', "$year-$month", 'after')->get();
    $cal_data = array();
    foreach ($query->result() as $row) {
        $cal_data[substr($row->date,8,2)] = $row->data;
    }
    return $cal_data;
}

It works OK and produces an array for a month, $cal_data, consisting of days as the keys and values (in this case the names of colors) and var_dump typically looks like this: 它工作正常并生成一个月的数组,$ cal_data,包括作为键和值的天数(在这种情况下是颜色的名称)和var_dump通常如下所示:

array (size=6)
26 => string 'amber' (length=5)
27 => string 'red' (length=3)
28 => string 'red' (length=3)
25 => string 'amber' (length=5)
'04' => string 'red' (length=3)
'07' => string 'red' (length=3)

which the calendar requires. 日历需要的。 However, there is a problem with days that have leading zeros as the calendar appears to need them without. 但是,由于日历似乎没有需要它们,因此天数有前导零。 So the values do not show for 04 and 07. As a test, I rewrote the foreach loop to say: 因此值不会显示04和07.作为测试,我重写了foreach循环说:

$cal_data[substr($row->date,9,1)] = $row->data;

so the key would pick up only the final character of the date string, and in that case the values for 4 and 7 did indeed show correctly. 所以键只能获取日期字符串的最后一个字符,在这种情况下,4和7的值确实显示正确。

Is there a simple way to remove the leading zeros so the keys would be 4 and 7? 有没有一种简单的方法来删除前导零,所以键是4和7?

You can do this (note the cast to int): 你可以这样做(注意转换为int):

foreach ($query->result() as $row) {
    $cal_data[(int)substr($row->date,8,2)] = $row->data;
}

I'm guessing since you have substr(..., 8, 2 ) I assume it's a full date like 2017-07-30 or something like it. 我猜你既然SUBSTR(...,8,2),我认为这是一个完整的日期像2017年7月30日或类似的东西。
So that means you can use date() to manipulate the data. 这意味着您可以使用date()来操作数据。

$cal_data[date("j", $row->date)] = $row->data;

Date("j") is day number without leading zeros. 日期(“j”)是没有前导零的日期编号。
http://php.net/manual/en/function.date.php http://php.net/manual/en/function.date.php

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

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