Array processing problems, optimization

Source: Internet
Author: User
To solve the array processing problem, find and optimize this post. at last, mafeifan edited an array from 2014-12-2611: 36: 04. $ Result & nbsp; [[month & gt; 08, price & gt; 218], [month & gt; 12, price & gt; 140],] array processing problems, optimization

This post was last edited by mafeifan at 11:36:04

There is an array to be queried in this way.

$result = [
['month'=>08,'price'=>218],
['month'=>12,'price'=>140],
];


Finally, it needs to be converted into a string for foreground js
Format: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, null, null]
Displays the monthly sales status. if there is no value, the value is null.
For example, the price in March is 49.9.

My practices:
I feel a little troublesome. I want to optimize it.


// First construct an array similar to ['01' => 0, '02' => 0... '12' => 0]
$ FullMonth = [];
For ($ I = 1; $ I <= 12; $ I ++ ){
$ FullMonth [str_pad ($ I, 2, '0', STR_PAD_LEFT)] = 0;
}
// Traverse the array and put the corresponding month value in the new array.
$ I = 0;
Foreach ($ fullMonth as $ month => $ value ){
Foreach ($ result as $ record ){
If ($ month = $ record ['month']) {
$ FullMonth [$ month] = $ record ['price'];
}
}
$ I ++;
}
Return '['. implode (',', $ fullMonth). ']';

------ Solution ----------------------
$r = array_fill(0, 12, null);
$result = [
['month'=> '08', 'price'=> 218],
['month'=> '12', 'price'=> 140],
];
foreach($result as $v) {
$r[$v['month'] - 1] = $v['price'];
}
echo json_encode($r);
[null,null,null,null,null,null,null,218,null,null,null,140]

------ Solution ----------------------
Y plus the quote, so there will be no notice

$res = [['y'=>'2014-12-03','item'=>263],['y'=>'2014-12-04','item'=>168]];
echo json_encode($res, JSON_PRETTY_PRINT);
?>




[
{
"y": "2014-12-03",
"item": 263
},
{
"y": "2014-12-04",
"item": 168
}
]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.