Jesper Bruun Hansen
Jesper Bruun Hansen

Reputation: 376

Create array from for-loop cakePHP

I'm making a very simple search-function in cakePHP, and want to populate an array from a for-loop with arrays dynamically.

I'm thinking of creating an array to set put as second parameter int the find()-function.

This is my static result:

$result = $this->Book->find('all', array('conditions' => 
      array("Book.book_title LIKE" => "%war%"),
      "OR" => 
      array("Book.book_title LIKE" => "%and%"),
      "OR" =>
      array('Book.book_title LIKE' => "%peace%")
));
$this->set('searchResult', $result);

My first intuition was to do so:

$search = $this->request->query['q'];
$words = explode(" ", $search);
$count = count($words);

And then create a for-loop from this, but the "OR =>" is causing me a lot of trouble to integrate. Can anybody help me to make this for loop?

Thanks in advance, Jesper.

Upvotes: 0

Views: 962

Answers (1)

mark
mark

Reputation: 21743

Why making life so complicated? Use OR once as main key and a simple array of arrays below it:

$conditions = array(
    'OR' => array(
        array('Book.book_title LIKE' => '%term1%'),
        array('Book.book_title LIKE' => '%term2%'),
        ...
    )
)

The nested arrays are necessary to avoid reusing the same array key (which does not work in PHP).

If it is coming from an exploded search query term, use foreach to keep things DRY (dont repeat yourself)

$terms = explode(' ', $his->request->query('q'));
foreach ($terms as $term) {
    $conditions['OR'][] = array('Book.book_title LIKE' => '%' . $term . '%'),
}

Upvotes: 2

Related Questions