questions

Create foreach loop from Value

Rate this post

i have this code:

$pr  =  $tst_db->mlm_get_parent(1);        // give me the value = 4 (parent_id of id 1)
$pr1 =  $tst_db->mlm_get_parent($pr);     // give me the value = 7 (parent_id of id 4)
$pr2 =  $tst_db->mlm_get_parent($pr1);   // give me the value = 5 (parent_id of id 7)
$pr3 =  $tst_db->mlm_get_parent($pr2);  // give me the value = 2 (parent_id of id 5)
$pr4 =  $tst_db->mlm_get_parent($pr3); // give me the value = 0 (becouse id 2 not have parent id)
echo $pr; echo $pr1; echo $pr2; echo $pr3; echo $pr4;

Its possible to make like a foreach loop
with automatic creation of ($pr(num) = $tst_db->mlm_get_parent($pr(num);)
and stop it when some $pr are equal to 0?
I need to echo too all parent_it created in this automatic loop.

This is what im expeting to have like results:
All parent_id of id 1 are: 4,7,5,2

Thanks in advance

 

✔️Solution:

This will print out all the parents of id 1 to the screen:

$id = 1;

while($id != 0) {
    $id  =  $tst_db->mlm_get_parent($id);
    echo $id;
}

// this will print: 47520

If you want the values to be stored in an array whose keys are of the exact format shown in the question:

$arr = array();
$id = 1;
$pr = 'pr';
$count = 0;

while($id != 0) {
    $id  =  $tst_db->mlm_get_parent($id);
    $arr[$pr] = $id;
    $ccount++;
    $pr = 'pr'.$count;
}

print_r($arr);  // prints: Array([pr] => 4 [pr1] => 7 [pr2] => 5 [pr3] => 2 [pr4] => 0)
echo join(",", $arr);   // prints 4,7,5,2,0

To produce independent variables based on the array keys you could use the extract() method:

extract($arr);

echo $pr;   // prints 4
echo $pr3;  // prints 2

Note:

  • The extract() method will overwrite any existing variables with names equal to the array’s key values.
  • Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).

You can also create a foreach loop that iterates through the populated $arr array:

foreach($arr as $key => $val) {
    // Do something here.
    // Although this foreach is not necessary since you could
    // have already done what you want to do within the above 
    // while loop
}

Leave a Reply

Your email address will not be published.

Back to top button