Mevia
Mevia

Reputation: 1564

Echo array as a string

I've got problem with echo'ing array as a string, the code i had before looks like this:

$years = array('2013', '2014');
foreach($years as $year) {
    //do rest of the code

I thought this is time to make the rest of the code more dynamic and "hands-off", so i prepared little function which selects from database years instead of typing it manually when new year is coming.

This is the code for year extract:

function order_count_for_year($us_id) {
$orders_for_year = array();

$query = "SELECT DISTINCT YEAR(`date_posted`) FROM `orders` WHERE `us_id` = {$us_id}";

$query = mysql_query($query);

while($row = mysql_fetch_assoc($query)) {
    $orders_for_year[] = $row;
}

return $orders_for_year;
}

So if i do foreach for this function it returns 2013 and 2014 corectly but i cant have it that way so i did this:

echo implode(', ', order_count_for_year($us_id));

And it doesnt work, it returns: array, array, i dont understand why it doesnt work, it works for different arrays within the apliacation but not with this one ...

finally i came up with bullshit like that:

$some_variable = '';
foreach(order_count_for_year($us_id) as $test) { $some_variable .= $test['YEAR(`date_posted`)'] . ', '; }
echo $some_variable;

It works, but i didnt want to make it that complicated, i dont feel that this is good idea. Anybody has idea why isnt it working with implode, or how to make it work without loop?

Please dont post with answers that i have to use variables for implode, its not needed and even if - i tested it, doesnt work.

Upvotes: 1

Views: 85

Answers (2)

Sven
Sven

Reputation: 70853

If you don't know what the data looks like you are dealing with, there is a simple method: Use var_dump($variable).

If used, you'd immediately spot that you don't have an array with two year-strings inside, but two layers of arrays.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

That's because you are adding $row to the array each time, which is itself an array.

You might be interested in mysql_fetch_row:

while($row = mysql_fetch_row($query)) $orders_for_year[] = $row[0];

With this, it doesn't matter what the column is called.

Alternatively, use an alias:

mysql_query("SELECT DISTINCT YEAR(`date_posted`) AS `year` FROM ...

Then you can access it as $row['year'] in your associative array.

Also, have a +1 for actually using backticks around your column names.

Upvotes: 3

Related Questions