Jump to content

Can I use a variable in a find selector


hansv
 Share

Recommended Posts

I extended my users-template with a lot af fields?  One of them is 'instrument'

The code beyond is working fine (see screenshot 1).  'instrument' is a page-select-field in the user template (the pages are violin, cello, clarinet, ...).  But this is not nice and efficient coding!!

// Violin
$person = $users->find('instrument=violin');
echo "violin";
foreach ($person as $p) {
  // $user fields are shown
    echo $p->first_name;
}

// cello
$person = $users->find('instrument=cello');
echo "cello";
foreach ($person as $p) {
  // $user fields are shown
   echo $p->first_name;
}

// clarinet
$person = $users->find('instrument=clarinet');
echo "clarinet";
foreach ($person as $p) {
  // $user fields are shown
    echo $p->first_name;
}

// and so on

screenshot 1.PNG

With a foreach the code could me more efficient, but the find-selector givns a problem with the variable $instr.  
 

// all instrument in a foreach
foreach ($user->instrument as $instr){
   $person = $users->find('instrument=$instr');  // does not work, neither do find('$instr') and find($instr)
      echo $instr->title;
	 foreach ($person as $p) {
         // $user fields are shown
         echo $p->first_name;
     }
}

With $person = $users-find($instr);  only the value of $instr is shown (e.g. violin) but not  the values of $p (e.g. first name of person. (see screenshot 2)

screenshot 2.PNG

 

How can I use a variable as find-selector?

 

Link to comment
Share on other sites

Hi,

 

try this.

$person = $users->find('instrument=' . $instr);

or

$person = $users->find("instrument=$instr");
// or
$person = $users->find("instrument={$instr}");

 

Variables inside single quote is just text / string. With double quotes php parses variables. 

  • Like 2
Link to comment
Share on other sites

Thx adrian and pwfoo for this quick answer.  This code is working very well

$person = $users->find('instrument=' . $instr);

 

But my foreach loop doesn't work.  I only get the first instrument.  

Link to comment
Share on other sites

I think the problem is that you need to foreach all the instruments, not just the ones in the user's instrument field. Probably something like this:

foreach ($pages->get("/instruments/")->children() as $instr){
   $person = $users->find('instrument='.$instr);
  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...