This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
This is my code
https://eval.in/157357
You can use a json parser if you wanna see the tree. This tree is returned by the Magento SOAP Api.
http://www.magentocommerce.com/api/soap/catalog/catalogCategory/catalog_category.tree.html
<?php
function getCategoryId($tree,$needle,&$val)
{
if(!empty($tree["name"]) && $tree["name"] === $needle)
{
$val = $tree["category_id"];
return $tree["category_id"];
}
else
{
if(isset($tree["children"]["category_id"]))
{
getCategoryId($tree["children"],$needle,$val);
}
else
{
foreach ($tree["children"] as $child) {
getCategoryId($child,$needle,$val);
}
}
}
}
function main()
{
$testjson = <<<EOL
{"category_id":"1","parent_id":"0","name":"Root Catalog","is_active":null,"position":"0","level":"0","children":[{"category_id":"2","parent_id":"1","name":"catroot","is_active":"1","position":"1","level":"1","children":[{"category_id":"3","parent_id":"2","name":"cat1","is_active":"1","position":"1","level":"2","children":[{"category_id":"7","parent_id":"3","name":"cat11","is_active":"0","position":"1","level":"3","children":[]},{"category_id":"8","parent_id":"3","name":"cat12","is_active":"0","position":"2","level":"3","children":[]}]},{"category_id":"9","parent_id":"2","name":"cat2","is_active":"0","position":"2","level":"2","children":[{"category_id":"11","parent_id":"9","name":"cat21","is_active":"0","position":"1","level":"3","children":[{"category_id":"12","parent_id":"11","name":"cat211","is_active":"0","position":"1","level":"4","children":[]},{"category_id":"13","parent_id":"11","name":"cat212","is_active":"0","position":"2","level":"4","children":[]}]}]},{"category_id":"10","parent_id":"2","name":"cat3","is_active":"0","position":"3","level":"2","children":[{"category_id":"14","parent_id":"10","name":"cat31","is_active":"0","position":"1","level":"3","children":[]},{"category_id":"15","parent_id":"10","name":"cat32","is_active":"0","position":"2","level":"3","children":[{"category_id":"16","parent_id":"15","name":"cat321","is_active":"0","position":"1","level":"4","children":[{"category_id":"17","parent_id":"16","name":"cat3211","is_active":"0","position":"1","level":"5","children":[]}]}]}]}]}]}
EOL;
$result = (json_decode($testjson,true));
$res = getCategoryId($result,"cat211",$val);
var_dump($res);
var_dump($val);
}
main();
?>
Why my function getCategoryId return NULL ? I don't want use the reference $val that was juste for testing.
You need to return the result from the recursive calls:
<?php
function getCategoryId($tree,$needle,&$val)
{
if(!empty($tree["name"]) && $tree["name"] === $needle)
{
//var_dump($tree);
//var_dump($tree["category_id"]);
$val = $tree["category_id"];
return $tree["category_id"];
}
else
{
if(isset($tree["children"]["category_id"]))
{
return getCategoryId($tree["children"],$needle,$val);
}
else
{
foreach ($tree["children"] as $child) {
$return = getCategoryId($child,$needle,$val);
if($return){
return $return;
}
}
}
}
}
function main()
{
$testjson = <<<EOL
{"category_id":"1","parent_id":"0","name":"Root Catalog","is_active":null,"position":"0","level":"0","children":[{"category_id":"2","parent_id":"1","name":"catroot","is_active":"1","position":"1","level":"1","children":[{"category_id":"3","parent_id":"2","name":"cat1","is_active":"1","position":"1","level":"2","children":[{"category_id":"7","parent_id":"3","name":"cat11","is_active":"0","position":"1","level":"3","children":[]},{"category_id":"8","parent_id":"3","name":"cat12","is_active":"0","position":"2","level":"3","children":[]}]},{"category_id":"9","parent_id":"2","name":"cat2","is_active":"0","position":"2","level":"2","children":[{"category_id":"11","parent_id":"9","name":"cat21","is_active":"0","position":"1","level":"3","children":[{"category_id":"12","parent_id":"11","name":"cat211","is_active":"0","position":"1","level":"4","children":[]},{"category_id":"13","parent_id":"11","name":"cat212","is_active":"0","position":"2","level":"4","children":[]}]}]},{"category_id":"10","parent_id":"2","name":"cat3","is_active":"0","position":"3","level":"2","children":[{"category_id":"14","parent_id":"10","name":"cat31","is_active":"0","position":"1","level":"3","children":[]},{"category_id":"15","parent_id":"10","name":"cat32","is_active":"0","position":"2","level":"3","children":[{"category_id":"16","parent_id":"15","name":"cat321","is_active":"0","position":"1","level":"4","children":[{"category_id":"17","parent_id":"16","name":"cat3211","is_active":"0","position":"1","level":"5","children":[]}]}]}]}]}]}
EOL;
$result = (json_decode($testjson,true));
$res = getCategoryId($result,"cat211",$val);
var_dump($res);
var_dump($val);
}
main();
?>
This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I have Used recursive function to get the category full path like Access Control/CARDS/FOBS from above table structure but my recursive function return null value.
function xyz($id,$parent) {
if($parent == '0') {
//my code working fine
//return
}
else
{
$catid = $id; //here 25 coming
$cat_array = array();
$category_array = $this->Recursive($catid,$cat_array);
//echo $category_array;exit; getting Null result
return $category_array ;
}
}
function Recursive($catid,$cat_array)
{
$sql = mysql_query("Select bg_category_id,parent_id,title from categories_list
Where bg_category_id = '".$catid."'");
$result = mysql_fetch_array($sql);
array_push($cat_array,$result['title']);
if($result['parent_id'] != '0') {
$this->Recursive($result['parent_id'],$cat_array) ;
} else {
if(count($cat_array) > 0){
$k = implode("/",$cat_array);
}
//echo $k;exit; getting desired result FOBS/CARDS/Access Control
return $k;
}
}
You need to return the recursive function when you recurse, otherwise it will return nothing.
if($result['parent_id'] != '0') {
return $this->Recursive($result['parent_id'],$category_array) ;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm not 100% comfortable with a PHP class defined here: mysqli
I stripped out the guts to shorten it somewhat and get a parse error at runtime.
<?php
function query($x)
{
if ($x > 8) {
return 'greater than eight!';
} else {
return true;
}
} else {
exit();
}
}
print query(7);
It's the same construct (I think) as the original, isn't it? Apart from the signature and the body of the method of course. I haven't come across an if else else clause before and it somehow doesn't 'feel right' for me at least logically wise. Moreover my code won't compile. Maybe you can set me straight?
Do you have any examples of how it may be used?
Secondly, from the original class - where or how does the $resource variable come into it? In what context would the object get passed a $resource variable?
My client code may be:
$db = new MySQLi;
$db->query("SELECT * FROM my_table");
but I don't see how $resource comes into play?
I assume you're trying to do something different but I hope this helps to explains how you can tie three conditions together.
function query($x) {
if ($x > 8) { // If $x is greater than 8
return 'greater than eight!';
} else if ($x < 8) { // If $x is lower than 8
return true;
} else {
return "The number is 8!";
}
}
print query(7);
You have a second else construct, it should look like:
if($x > 8) {
// your if(true) code
} else {
// your if(false) code
}
there is a missing if else block which is highlighted with ** here that's y you are getting the parser error as same is the problem with your code
<?php
final class MySQLi {
private $mysqli;
public function __construct($hostname, $username, $password, $database) {
$this->mysqli = new mysqli($hostname, $username, $password, $database);
if ($this->mysqli->connect_error) {
trigger_error('Error: Could not make a database link (' . $this->mysqli->connect_errno . ') ' . $this->mysqli->connect_error);
}
$this->mysqli->query("SET NAMES 'utf8'");
$this->mysqli->query("SET CHARACTER SET utf8");
$this->mysqli->query("SET CHARACTER_SET_CONNECTION=utf8");
$this->mysqli->query("SET SQL_MODE = ''");
}
public function query($sql) {
$result = $this->mysqli->query($sql);
if ($this->mysqli->errno) {
//$mysqli->errno
}
if (is_resource($resource)) {
$i = 0;
$data = array();
while ($row = $result->fetch_object()) {
$data[$i] = $row;
$i++;
}
$result->close();
$query = new stdClass();
$query->row = isset($data[0]) ? $data[0] : array();
$query->rows = $data;
$query->num_rows = $result->num_rows;
unset($data);
return $query;
} else {
return true;
}
***} else {
trigger_error('Error: ' . mysql_error($this->link) . '<br />Error No: ' . mysql_errno($this->link) . '<br />' . $sql);
exit();
}***
}
public function escape($value) {
return $this->mysqli->real_escape_string($value);
}
public function countAffected() {
return $this->mysqli->affected_rows;
}
public function getLastId() {
return $this->mysqli->insert_id;
}
public function __destruct() {
$this->mysqli->close();
}
}
?>
There is something missing in your code. If you someone runs your code.
Parse error: syntax error, unexpected T_ELSE on line 8
So your function should look like below
function query($x)
{
if ($x > 8)
{
//runs when $x value is greater than 8
return 'greater than eight!';
}
else
{
// if the condition didnt meet, according to my knowledge you should return false here
return true;
}
exit();
}
print query(7);
If you want to have a else if,
if (condition)
{
code to be executed if condition is true;
}
else if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
function func() {
// ...
}
I have the function name "func", but not its definition.
In JavaScript, I'd just use alert() to see the definition.
Is there a similar function in PHP?
You can use the methods getFileName(), getStartLine(), getEndLine() defined in ReflectionFunctionAbstract to read the source code of functions/methods from their source file (if there is any).
e.g. (without error handling)
<?php
printFunction(array('Foo','bar'));
printFunction('bar');
class Foo {
public function bar() {
echo '...';
}
}
function bar($x, $y, $z) {
//
//
//
echo 'hallo';
//
//
//
}
//
function printFunction($func) {
if ( is_array($func) ) {
$rf = is_object($func[0]) ? new ReflectionObject($func[0]) : new ReflectionClass($func[0]);
$rf = $rf->getMethod($func[1]);
}
else {
$rf = new ReflectionFunction($func);
}
printf("%s %d-%d\n", $rf->getFileName(), $rf->getStartLine(), $rf->getEndLine());
$c = file($rf->getFileName());
for ($i=$rf->getStartLine(); $i<=$rf->getEndLine(); $i++) {
printf('%04d %s', $i, $c[$i-1]);
}
}
I don't know of one.See code at bottom. There is a function to list all the defined functions. There's another to get the values of all the arguments to the current function, and the number of arguments. And there's one to see if a function exists. But there doesn't seem to be one to name the current function, nor any means of listing formal parameters.
Even when a runtime error occurs, it doesn't list a call stack, nor state the function that's active:
PHP Warning: Division by zero in t.php on line 6
Edit: For the code to identify where it is, add this:
echo "At line " .__LINE__ ." of file " . __FILE__ ."\n";
It gives the output
At line 7 of file /home/wally/t.php
Edit 2: I found this function in my code which looks to be what you want:
function traceback ($showvars)
{
$s = "";
foreach (debug_backtrace($showvars) as $row)
{
$s .= "$row[file]#$row[line]: ";
if(isset($row['class']))
$s .= "$row[class]$row[type]$row[function]";
else $s .= "$row[function]";
if (isset($row['args']))
$s .= "('" . join("', '",$row['args']) . "')";
$s .= "<br>\n";
}
return $s;
}
For example, it produces:
[wally#zf ~]$ php -f t.php
/home/wally/t.php#24: traceback('1')<br>
/home/wally/t.php#29: t('1', '2', '3')<br>
/home/wally/t.php#30: x('2', '1')<br>
/home/wally/t.php#31: y('2', '1')<br>
/home/wally/t.php#33: z('1', '2')<br>