Array processing problems, optimization

Source: Internet
Author: User
To solve the array processing problem, we need to optimize an array that is 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.

// Construct a structure similar to ['01' => 0, '02' => 0 .... '12' => 0] an array in this format $ fullMonth = []; for ($ I = 1; $ I <= 12; $ I ++) {$ fullMonth [str_pad ($ I, 2, '0', STR_PAD_LEFT)] = 0 ;} // traverse the corresponding month of the array and put it 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 ). ']';


Reply to discussion (solution)

Why not use json format?

$result = [    ['month'=>08,'price'=>218],    ['month'=>12,'price'=>140],];echo json_encode($result); // [{"month":0,"price":218},{"month":12,"price":140}]


   
   New Document    
 08, 'price' => 218], ['month' => 12, 'price' => 140],];?>

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.