Reputation: 6799
I have created a class to find out the position / level of a particular key inside an array. I was actually trying to create a function but I ended up creating an entire class as I had to keep track of my counter. Although the class is working perfectly, I really need to get this done using a function only.
Could you please help me with a solution so that I can achieve the same result using function / functions only.
Here's my code for the class :
class Boom {
private $count = 0;
function get_depth($array, $keyValue)
{
foreach ($array as $key=>$value) {
if($key==$keyValue)
{
return $this->count;
}
elseif(is_array($value))
{
$this->count++;
echo $this->get_depth($value,$keyValue);
$this->count--;
}
}
}
}
To use this class:
$obj = new Boom();
echo $obj->get_depth($array, 'your_key'); // 'your_key' example: 'Refrigerator'
You can use an array like following:
$asset = array(
'Electronics' => array(
"TV"=>array("TV1"=>500,"TV2"=>2500),
"Refrigerator"=>200,
"Washing Machine"=>array("WM1"=>array("b1"=>array("b11"=>80,"b22"=>10),"WM12"=>10),"WM2"=>5500),
"Savings Accounts"=>200,
"Money Market Accounts"=>200,
),
'Sports'=> array(
"Cricket"=>array("CBat"=>500,"CBall"=>2500),
"Tennis"=>900,
"Football"=>array("FBall"=>1500,"FJersy"=>5500),
),
'Random' =>"0"
);
Upvotes: 1
Views: 78
Reputation: 14469
Simple. Just pass in the key on each recursive call:
function get_depth($array, $keyValue, $count = 0)
{
foreach ($array as $key=>$value) {
if ($key==$keyValue) {
return $count;
} elseif (is_array($value)) {
$count++;
echo get_depth($value, $keyValue, $count);
$count--;
}
}
}
Note: I haven't verified the functionality of your code, I just copied your exact code in a way that does not require a class to store the variable.
Another way to do it might be to use a static variable (also not tested), but I would suggest going with the first method, above:
function get_depth($array, $keyValue)
{
static $count = 0;
foreach ($array as $key=>$value) {
if ($key==$keyValue) {
return $count;
} elseif (is_array($value)) {
$count++;
echo get_depth($value, $keyValue);
$count--;
}
}
}
Upvotes: 1