I have this PHP code:
foreach( $wpdb->get_results(
) as $key => $row) {
echo \"[\'\". $row->DATE . \"\',\". $row->total_sales . \"],\";
}
There are a few approaches:
Of those options, I'd probably use #1, because it makes the code just a bit more self-documenting.
You'll need variable to store comma state:
$comma = ""; ## don't need comma before first element
foreach( $wpdb->get_results(
) as $key => $row) {
echo $comma."['". $row->DATE . "',". $row->total_sales . "]";
$comma = ",";
}
php has a trim function, give it a string and the comma.
$s = trim ($s,",")
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;
put your string in substr() function
$string = "";
while ($row = mysql_fetch_array($result)) {
$string .= $name . ', ';
}
echo substr($string, 0, strlen($string) - 2);
I usually do it this way..
$result = array();
foreach( $wpdb->get_results() as $key => $row ){
$result[] = "['". $row->DATE . "',". $row->total_sales . "]";
}
echo implode( ',', $result );
It's a bit more succinct, (but perhaps more memory inefficient due to the temporary array).