Removing last comma in PHP?

前端 未结 7 2138
忘掉有多难
忘掉有多难 2020-11-28 16:36

I have this PHP code:

foreach( $wpdb->get_results(
) as $key => $row) {

echo \"[\'\". $row->DATE . \"\',\". $row->total_sales . \"],\";

}
         


        
7条回答
  •  生来不讨喜
    2020-11-28 17:03

    I like the implode idea, but I often use the ternary operator to keep everything succinct. Many people don't like the ternary, but it is a very well-known construct in many languages so I use it. In this case, if I'm on the first iteration $results will be empty so I don't insert a comma, otherwise I put a comma in the content before the new data:

    $results = '';
    foreach( $wpdb->get_results() as $key => $row) {
    
        $results .= (empty($results) ? '' : ',') . "['". $row->DATE . "',". $row->total_sales . "]";
    
    }
    echo $results;
    

提交回复
热议问题