Apply own function to element of array

I have an array that is extracted using a PDO query from the database and I want to perform a function that cuts down the number of words in one of the elements.

the function works fine but i don’t know how to apply the function to every row in the array

The $rows is an array of all the records

//this performs a query using PDO to get all the records but adding a LIMIT to the query
$rows = $this->dao->fetchAll($offset, $entries_per_page

and this is how i call the function normally ususally done if the foreach/while loop on the row element i want to truncate

$this->words->trunc($row['content']);

This is my function that truncates the string (in the ‘Words’ class)

public 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;
	}

I have tried this

$rows = $this->words->trunc($this->dao->fetchAll($offset, $entries_per_page), 60);

but i get this error message

Warning: explode() expects parameter 2 to be string, array given in C:\www\adrock\php\classes\class.words.php on line 48

Any idea how i can just truncate the ‘content’ field in the array using my function

Sounds like a good case for recursion.


public function trunc($phrase, $max_words)
    {
    if( is_array( $phrase ) ) {
      $out = array();
      foreach( $phrase as $k => $v ) {
        $out[ $k ] = $this->trunc( $v, $max_words );
      }
      return $out;
    }

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

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

    return $phrase;
    }

That will call your truncate on each field which may not be what you’re after. If not, I think you’ll just have to loop through your results and call your function on the one element.

you cannot pass $this->dao->fetchAll($offset, $entries_per_page) directly to the trunc function, because fetchAll returns an array.

what you need to do is to pass it to a variable an use that variable to pass the content data to the trunc function

$result = $this->dao->fetchAll($offset, $entries_per_page);

$rows = $this->words->trunc($result[‘content’], 60);