2

I've been looking all afternoon and can't find a solution to my problem.

I query my database using PDO to get a set of rows containing data. I get the 'title', 'content' and the 'postdate' for many rows in my query.

I query the database like this

$sth = $dbh->prepare("SELECT title, content, postdate FROM mytable");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
$result = $sth->fetchAll(); 

At the moment I have 6 rows and for each row, I want to trim the amount of words in the 'content' field. I have a function to trim the amount of words like this

function trunc($phrase, $max_words) {

    $phrase_array = explode(' ',$phrase);

    if(count($phrase_array) > $max_words && $max_words > 0)
        $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...';

    return $phrase;
}

To use my function I use

trunc($string_to_be_truncated, 60);

What I am having trouble with is replacing what is in the array return from the database with the cut down words in the 'content' field

Basically, I want to cut the amount of words for each of the 'content' fields in the array.

I have been getting a variety of errors for whatever i try such as illegal offset etc.

I haven't got any examples of what I've tried as I've tried so many things but nothing worked.

4

1 回答 1

1

You will need to iterate through the array like this

foreach($result as $key=>$result_row)
{
    $result[$key]['content'] = trunc($result_row['content'], 60);
}

That should replace the value in the original array with the shortened value. You have to access the original array.

于 2013-09-17T16:06:30.930 回答