Heim  >  Artikel  >  Backend-Entwicklung  >  数组处理有关问题,求优化

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

WBOY
WBOYOriginal
2016-06-13 12:12:38736Durchsuche

数组处理问题,求优化

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


最终需要转换成一个字符串,用于前台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 />

------解决思路----------------------
$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);
[null,null,null,null,null,null,null,218,null,null,null,140]

------解决思路----------------------
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 />


<br /><br />[<br />    {<br />        "y": "2014-12-03",<br />        "item": 263<br />    },<br />    {<br />        "y": "2014-12-04",<br />        "item": 168<br />    }<br />]<br />
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn