Page 1 of 1

Creating an Array via recursive loop

Posted: Mon Apr 28, 2008 3:02 am
by nav_kb
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


Hi,

I'm trying to create an array with the following structure

Code: Select all

 
//Fields to search
$fields = array("title", "excerpt", "body", "fname", "lname");
 
//Word to search
$word = "hello";
 
$conditions = array("active"=>1);
 
//**** THIS IS WHAT I WANT TO CREATE VIA A LOOP ***
$conditions["or"] = array($fields[0]=>"LIKE %".$word."%");
$conditions["or"]["or"] = array($fields[1]=>"LIKE %".$word."%");
$conditions["or"]["or"]["or"] = array($fields[2]=>"LIKE %".$word."%");
$conditions["or"]["or"]["or"]["or"] = array($fields[3]=>"LIKE %".$word."%");
$conditions["or"]["or"]["or"]["or"]["or"] = array($fields[4]=>"LIKE %".$word."%");
 
I'm sure recursion is the way to go but how to loop for the number of keys per index?

Any help would be highly appreciated.

Kind Regards,

Navneet


~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: Creating an Array via recursive loop

Posted: Mon Apr 28, 2008 4:13 am
by nav_kb
Thanks for reading.. I figured it out and perhaps can help some other future reader who wanders here:

Code: Select all

 
//Fields to search
$fields = array("title", "excerpt", "body", "fname", "lname");
 
//Word to search
$word = "hello";
 
$conditions = array("active"=>1);
 
for ($f = 0; $f<count($fields); $f++) {
    eval("\$conditions"._getEvalKey("or", ($f+1))." = array('".$fields[$f]."'=>'LIKE %".$word."%');");
}
 
//Utility function to append string keys via eval to array
function _getEvalKey($keyname, $times){
    $str = "";
    for($i=0; $i<$times; $i++) {
        $str .= "['".$keyname."']";
    }
    return $str;
}
 
//Let's see our array:)
print "<pre>";
print_r($conditions);
print "</pre>";
 
There you have a recursive loop on array with custom keys :)