Home > Backend Development > PHP Tutorial > 数组处理有关问题,求优化

数组处理有关问题,求优化

WBOY
Release: 2016-06-13 12:12:38
Original
804 people have browsed it

数组处理问题,求优化

本帖最后由 mafeifan 于 2014-12-26 11:36:04 编辑 有一个这样查询出来的数组。
<br />$result = [<br />	['month'=>08,'price'=>218],<br />	['month'=>12,'price'=>140],<br />];<br />
Copy after login


最终需要转换成一个字符串,用于前台js
格式类似:[49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, null, null]
显示的是每月的销售情况,没有值就为null
比如一月份的price为49.9

我的做法:
感觉有点麻烦,求优化

<br />        //先构造类似  ['01'=>0,'02'=>0 .... '12'=>0]  这种格式的数组<br />        $fullMonth = [];<br />        for($i=1;$i<=12;$i++){<br />            $fullMonth[str_pad($i,2,'0',STR_PAD_LEFT)] = 0;<br />        }<br />        //  遍历数组  对应月份有值就放到新建的数组里<br />        $i = 0;<br />        foreach($fullMonth as $month=>$value){<br />            foreach($result as $record){<br />                if($month == $record['month']){<br />                    $fullMonth[$month] = $record['price'];<br />                }<br />            }<br />            $i++;<br />        }<br />        return '[' . implode(',',$fullMonth) . ']';<br />
Copy after login

------解决思路----------------------
$r = array_fill(0, 12, null);<br />$result = [<br />    ['month'=> '08', 'price'=> 218],<br />    ['month'=> '12', 'price'=> 140],<br />];<br />foreach($result as $v) {<br />  $r[$v['month'] - 1] = $v['price'];<br />}<br />echo json_encode($r);
Copy after login
[null,null,null,null,null,null,null,218,null,null,null,140]
Copy after login

------解决思路----------------------
y加上引號,這樣才不會有notice
<br /><?php<br />$res = [['y'=>'2014-12-03','item'=>263],['y'=>'2014-12-04','item'=>168]];<br />echo json_encode($res, JSON_PRETTY_PRINT);<br />?><br />
Copy after login


<br /><br />[<br />    {<br />        "y": "2014-12-03",<br />        "item": 263<br />    },<br />    {<br />        "y": "2014-12-04",<br />        "item": 168<br />    }<br />]<br />
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template