I have this array
Array
(
[name] => Step1 is here
[standard] => Array
(
[product_id] => 85,99
[product_name] => Step1 is here
[product_price] => 976.0000
[product_description] => :something
[product_image] => http://someurl.com/shop_pos/image/data/13D.png
)
[professional] => Array
(
[product_id] => 61
[product_name] => Step1 is here
[product_price] => 289.0000
[product_description] => somethingothere
[product_image] => http://someurl.com/shop_pos/image/data/13B.png
)
[premium] => Array
(
[product_id] => 677
[product_name] => Step1 is here
[product_price] => 289.0000
[product_description] => somethingothere
[product_image] => http://someurl.com/shop_pos/image/data/13A.png
)
)
Is there an easy of referencing in the proper order that i need. SO the order i need is standard, professional, premium.. so if one is not present can I do to the other like this
if (!isset($my_array['standard'])) {
$use_me = $my_array['standard']
}elseif(!isset($my_array['professional'])) {
$use_me = $my_array['professional']
}elseif(!isset($my_array['professional'])) {
$use_me = $my_array['premium']}
}
i have the above code that i think may work but is there a better way
That should do it:
$keys = array_slice(array_keys($my_array), 1, 1);
$use_me = $my_array[$keys[0]];
In short:
Get the array keys (name, standard, professional, premium). (array_keys)
Get the second key (bypassing name, so it returns standard or whatever the second key is). (array_slice)
Reference $my_array using that key and store it in $use_me.
I would do this:
foreach (array('standard', 'professional', 'premium') as $name) {
if (isset($my_array[$name])) {
$use_me = $my_array[$name];
break;
}
}
or a little more structured:
function selectPlan($array) {
foreach (array('standard', 'professional', 'premium') as $name) {
if (isset($array[$name])) return $array[$name];
}
}
$use_me = selectPlan($my_array);
Yes, you can do it the way you have presented in your code. However, your if statement logic is not correct. Your code should be like this:
if (isset($my_array['standard'])) {
$use_me = $my_array['standard'];
} elseif(isset($my_array['professional'])) {
$use_me = $my_array['professional'];
} elseif(isset($my_array['premium'])) {
$use_me = $my_array['premium'];
}
try with array_key_exists
foreach($input as $k=>$v) {
if (array_key_exists('standard', $k)) {
$output [$k] = $k;
}
if (array_key_exists('professional', $k)) {
$output [$k] = $k;
}
if (array_key_exists('premium', $k)) {
$output [$k] = $k;
}
}
or u can go through array-intersect-key
If I understand correctly what you want to do, and if the order of the keys is not guaranteed to be exactly like the one in the example, you can do something like:
// initialization
$use_me = 'default value';
// go through each package
foreach (array('standard', 'professional', 'premium') as $package) {
// when we find a package that does exist
if (isset($my_array[$package])) {
// mark it as found and exit the loop
$use_me = $package;
break;
}
}
This will go through all the packages and set the $use_me variable to the first found value. If no value is found, it sets it to a default value.
Related
Following is my PHP code:
while($row = $resp->fetch_assoc())
{
$itemArray = array(
array(
'name' => $row["product_name"],
'id' => $row["id"],
'image' => $row['images'],
'discount' => $row["discount"],
'quantity' => $min_quantity,
'price' => $row["price"]
)
);
}
if(!empty($_SESSION["cart_item"]))
{
if(in_array($itemArray, $_SESSION["cart_item"]))
{
foreach($_SESSION["cart_item"] as $item)
{
if(in_array($item, $itemArray))
$_SESSION["cart_item"][$item]["quantity"] = $min_quantity;
break;
}
}
else
{
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
else
{
$_SESSION["cart_item"] = $itemArray;
}
After executing this code i am getting a response like this:
Array
(
[0] => Array
(
[name] => Girls Designer Dress
[id] => 4
[image] => s:146:"2017/march/meetfashion01-04-2017_12-19-07_am.jpg,2017/march/meetfashion01-04-2017_12-19-08_am
.jpg,2017/march/meetfashion01-04-2017_12-19-09_am.jpg";
[discount] => 10
[quantity] => 1
[price] => 1200
)
)
What I am trying to acheive is if user adds the same product in cart whose data we have got in response then instead of creating once more array and merging it one after another i want to just update the quantity of the same product from 1 to 2.
I am stuck in this part of code
foreach($_SESSION["cart_item"] as $item)
{
if(in_array($item, $itemArray))
$_SESSION["cart_item"][$item]["quantity"] = $min_quantity;
break;
}
I have tried it many times that if same product is encountered then increment the quantity by 1 for the same product and don't create one more array.
Can anyone help with this logic and code?
is $_SESSION["cart-item"] a single Array like?
Array
(
[name] => Girls Designer Dress
[id] => 4
[image] => s:146:"2017/march/meetfashion01-04-2017_12-19-07_am.jpg,2017/march/meetfashion01-04-2017_12-19-08_am
.jpg,2017/march/meetfashion01-04-2017_12-19-09_am.jpg";
[discount] => 10
[quantity] => 1
[price] => 1200
)
If so then don't call a foreach instead just check directly if that cart-item is in the $itemArray using array_search().
(The function search in a array and if needle is found return its index else return false).
$cartItemPosition = array_search($_SESSION['cart-item'], $itemArray);
if($cartItemPosition == false) {
// Not found in array, so create new entry
$itemArray.push($_SESSION['cart-item']);
}else {
// Found in array so edit existing entry
$itemArray[$cartItemPosition]['quantity'] = 999;
}
The below works if $itemArray has only 1 item :
Change to :
if(!empty($_SESSION["cart_item"]))
{
if(in_array($itemArray[0], $_SESSION["cart_item"]))
{
foreach($_SESSION["cart_item"] as $index => $item)
{
if(in_array($item, $itemArray))
$_SESSION["cart_item"][$index]["quantity"] = $_SESSION["cart_item"][$index]["quantity"] + 1;
break;
}
}
else
{
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
else
{
$_SESSION["cart_item"] = $itemArray;
}
Added [0] in first if statement of in_array.
Added $index in the foreach loop and used it.
Your code before never went to the if statement. If $itemArray is always containing an array inside an array (that's why we used [0]) then it should be like that.
If it is possible that $itemArray has more than 1 items then we will have to edit the answer as needed.
Also not sure, but if your fetching loop is possible to return more than one items then it's wrong becuse you will only have the last result. If you know that you will only have 1 result back then it's all good.
while($row = $resp->fetch_assoc())
{
$itemArray = array(
array(
'name' => $row["product_name"],
'id' => $row["id"],
'image' => $row['images'],
'discount' => $row["discount"],
'quantity' => $min_quantity,
'price' => $row["price"]
)
);
}
What I’m trying to achieve is that, it will loop trough the array. Then it will look if the items in the array are the same on three points: product_id, the size value and the color value.
I want to create a new array where the items are listed, the only thing I don’t want is the duplicated values. I want that the duplicated values if they are the same on those three points that the quantity will be count together. Like if I have 3 items same product id same size and same color and both of the three I ordered 3 items in my new array this is just standing 1 time and the quantity will be 9. So there will be no duplicated values in my new array.
Current loop
foreach($orders as $key => $order){
foreach($order['orderProducts'] as $key => $value){
echo '<pre>';
print_r($value['attributes']);
echo '</pre>';
}
}
results in the the following array
Array
(
[id] => 2
[product_id] => 4
[order_id] => 2
[name] => swag3
[description] => haha
[price] => 19.95
[proceeds] => 10.00
[quantity] => 2
[attributes] => [{"id":1,"name":"Size","value":"XS","active":1},{"id":8,"name":"Color","value":"Wit","active":1}]
)
Array
(
[id] => 3
[product_id] => 3
[order_id] => 3
[name] => swag2
[description] => lol
[price] => 19.95
[proceeds] => 10.00
[quantity] => 2
[attributes] => [{"id":2,"name":"Size","value":"S","active":1},{"id":7,"name":"Color","value":"Zwart","active":1}]
)
Array
(
[id] => 4
[product_id] => 3
[order_id] => 4
[name] => swag2
[description] => lol
[price] => 19.95
[proceeds] => 10.00
[quantity] => 1
[attributes] => [{"id":2,"name":"Size","value":"S","active":1},{"id":7,"name":"Color","value":"Zwart","active":1}]
)
Sort of what I’m looking for..
Array
(
[id] => 2
[product_id] => 4
[order_id] => 2
[name] => swag3
[description] => haha
[price] => 19.95
[proceeds] => 10.00
[quantity] => 2
[attributes] => [{"id":1,"name":"Size","value":"XS","active":1},{"id":8,"name":"Color","value":"Wit","active":1}]
)
Array
(
[id] => 3
[product_id] => 3
[order_id] => 3
[name] => swag2
[description] => lol
[price] => 19.95
[proceeds] => 10.00
[quantity] => 3
[attributes] => [{"id":2,"name":"Size","value":"S","active":1},{"id":7,"name":"Color","value":"Zwart","active":1}]
)
Solution
Note it's blade php as frontend.
Backend
$order // is the array with products
$items = [];
foreach($orders as $key => $order){
foreach($order['orderProducts'] as $op){
$i = [
'product'=> Product::findOrFail($op->product_id)->toArray(),
'attributes' =>$op->attributes,
'quantity'=>$op->quantity
];
$matchedResult = false;
$count = count($items);
for($a = 0; $a < $count; $a++){
// Items with the same product_id in the $item array
if($items[$a]['product']['id'] == $i['product']['id']){
//check if the attributes are also the same
if($items[$a]['attributes'] === $i['attributes']){
// The attributes ar ethe same so up the quantity
$items[$a]['quantity'] += $i['quantity'];
$matchedResult = true;
continue; // If its right there are no other matches
}
}
}
if($matchedResult === false){
// only push item if there is not a match.
$items[] = $i;
}
}
}
Frontend
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>quantity</th>
</tr>
</thead>
<tbody>
#foreach($items as $item)
<tr>
<td>{{$item['product']['name']}}
#if(count($item['attributes']) > 0) <small>
#foreach($item['attributes'] as $att)
{{$att['name']}} - {{$att['value']}}
#endforeach
</small>
#endif</td>
<td>{{$item['quantity']}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
You can achieve your goal without using nested loops. You may use hash function of product_id, size and color parameters and use that value as a new array key like this:
$orders = // original array;
$newOrders = []; // new array
foreach($orders as $order) {
$pi = $order["product_id"]; // get product_id
$attr = json_decode($order["attributes"]); // get attributes:
$size = $attr[0]->value; // get size value
$color = $attr[1]->Color; // get color
$hash = sprintf("%s.%s.%s", $pi, $size, $color); // Calculate hash
if ($newOrders[$hash]) {
$newOrders[$hash].quantity++; // If hash is already present then just increase quantity
} else {
// Otherwise add new order
$newOrders[$hash] = [
"order" => $order,
"quantity" => 1
];
}
}
I hope this can help you:
$sortedArray = [];
foreach ($order as $array) {
$tag = getTag($array);
push_to_array($sortedArray,$array,$tag);
}
function push_to_array(&$array1,$array2,$tag)
{
isset($array1[$tag]) ? $array1[$tag]['quantity'] += $array2['quantity'] : $array1[$tag] = $array2;
}
function getTag($array)
{
$attribs = json_decode($array['attributes'],true);
foreach ($attribs as $value) {
($value['name'] =='Size' ) && $size = $value['value'];
($value['name'] =='Color') && $color= $value['value'];
}
return $array['product_id'].$size.$color;
}
Try this (untested but logic should be correct):
$orders = // original array;
$new; // new array
foreach($orders as $order) {
$pi = $order["product_id"]; // get product_id
$attr = json_decode($order["attributes"]); // get attributes:
$size = $attr[0]->value; // get size value
$color = $attr[1]->Color; // get color
$duplicate = false;
foreach($newOrders as $newOrder() { // loop through nested array
$newPi = $newOrder["product_id"];
$newAttr = json_decode($newOrder["attributes"]);
$newSize = $newAttr[0]->value;
$newValue = $newAttr[1]->Color;
// check to see if same
if(
$pi == $newPi &&
$size == $newSize &&
$color == $newColor
) {
$newOrders["quantity"]++;
$duplicate = true;
break;
}
}
if(!$duplicate) {
$new[] = $order;
}
}
Edit: Sorry, I just reread your post and saw you don't want a full solution. Sorry. But I hope this can show you that nested loops are the way to go with this. As mentioned in the comments, there is no built in function for this in PHP (AFAIK).
This is not a solution, but another approach to let you think by Object Oriented Programming
It will helps you a lot in you current and next problems
Now, you have a business case, that it must be resolved in your business layer
I can assist you if you want
<?php
class Attribute {
private $_id;
private $_name;
private $_value;
private $_active;
// TODO implement getter and setter
// lTODO implement constructor
}
class Product {
private $_id;
private $_productId;
// ... order_id, name, ...
private $_attribute_a = array(); // it will be an array of attribute's object
// TODO implement getter and setter
// TODO implement constructor
private function getAttributeByName($name) {
// loop through attribute array object and return the right attribute
// foreach ($this->_attribute_a as $attr) {
// if ($attr->name === $name) return $attr;
// }
}
public function equals($o) {
if (!is_a($o, 'Product')) return FALSE;
if ($this == $o) return TRUE ;
if ($this->_productId === $o->_productId) {
$attr1 = $this->getAttributeByName('Size');
$attr2 = $this->getAttributeByName('Size');
if ($attr1->getValue() !== $attr2->getValue()) return FALSE;
$attr1 = $this->getAttributeByName('Color');
$attr2 = $this->getAttributeByName('Color');
if ($attr1->getValue() !== $attr2->getValue()) return FALSE;
return TRUE;
}
return FALSE;
}
}
Now, you can compare easily 2 Products Object, and later, updating equals() will not affect your code
You have some grate answers from other users.
However i would like to post this for Googlers or other users in the planning stage and for your own knowledge.
With your example your using a shopping basket. You should never have duplicate items in the array you should be using a Quantity measure on the item and before adding to your array you check the array if the matching item is there increase the quantity.
as your current way your code is processing though the array after for no good reason if i was to add 20 of the same item your current system would have an array of 20 to loop though every time i opened the basket.
This other method will also provide you will support for people to add multiple quantities of items at once, also on your basket page edit the quantities
Please note the assumptions below the code
function combineDuplicates($orders) {
$indexArray = array();
$uniqueArray = array();
foreach($orders as $value) {
$productID = $value['product_id'];
$attributes = $value['attributes'];
foreach($attributes as $attribute) {
switch($attribute['name']) {
case 'Size' : $size = $attribute['value'];
break;
case 'Color': $color = $attribute['value'];
break;
default : break;
}
}
if (!isset($indexArray[$productID][$size][$color])) {
$indexArray[$productID][$size][$color]['count'] = 0;
$uniqueArray[] = $value;
}
$indexArray[$productID][$size][$color]['count']++;
}
$orders = array();
foreach($uniqueArray as $key => $value) {
$productID = $value['product_id'];
$attributes = $value['attributes'];
foreach($attributes as $attribute) {
switch($attribute['name']) {
case 'Size' : $size = $attribute['value'];
break;
case 'Color': $color = $attribute['value'];
break;
default : break;
}
}
$uniqueArray[$key]['quantity'] = $indexArray[$productID][$size][$color]['count'];
}
return $uniqueArray;
}
Assumptions :
'attributes' is converted to associative array
product_id, Color & Size values are non-empty in each element
How can i add element to my array under a specific key?
This is my array output before i use foreach. As you can see, the error field is empty. I want to fill it out.
Array (
[0] => Array (
[transactionid] => 2223
[created] => 26-02-13 14:07:00
[cardid] => 10102609
[pricebefordiscount] => 68900
[error] =>
)
This is my foreach. As you can see i already tried to make this work by implementing $arrayname['index'] = $value;. But this does not work, nothing comes out when i spit out in a print_r. Why is this happening?
foreach ($samlet as $key)
{
if ($key['pricebefordiscount'] > '200000')
{
$samlet['error'] = "O/2000";
}
if ($key['cardid'] === '88888888')
{
$samlet['error'] = "Testscan";
}
}
This is the desired output:
Array (
[0] => Array (
[transactionid] => 2223
[created] => 26-02-13 14:07:00
[cardid] => 10102609
[pricebefordiscount] => 68900
[error] => "Testscan"
)
Change your foreach, so you have the indexes used in the "main" $samlet array:
foreach($samlet as $key => $array)
{
if ($array['cardid'] === '88888888')
{
$samlet[$key]['error'] = '0/2000';
}
}
And so on...
Try this :
foreach ($samlet as &$key){
if ($key['pricebefordiscount'] > '200000'){
$key['error'] = "O/2000";
}
if ($key['cardid'] === '88888888'){
$key['error'] = "Testscan";
}
}
According to PHP manual:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
So your code should looke like this:
<?php
foreach ($samlet as &$key)
{
if ($key['pricebefordiscount'] > '200000')
{
$key['error'] = "O/2000";
}
if ($key['cardid'] === '88888888')
{
$key['error'] = "Testscan";
}
}
TRY THIS
foreach ($samlet as $key=>$value)
{
if ($value['pricebefordiscount'] > '200000')
{
$samlet[$key]['error'] = "O/2000";
}
if ($value['cardid'] === '88888888')
{
$samlet[$key]['error'] = "Testscan";
}
}
Here is print_r output of my array:
Array
(
[0] => stdClass Object
(
[itemId] => 560639000019
[name] => Item no1
[code] => 00001
[qty] => 5
[id] => 2
)
[1] => stdClass Object
(
[itemId] => 470639763471
[name] => Second item
[code] => 76347
[qty] => 9
[id] => 4
)
[2] => stdClass Object
(
[itemId] => 56939399632
[name] => Item no 3
[code] => 39963
[qty] => 6
[id] => 7
)
)
How can I find index of object with [id] => 4 in order to remove it from array?
$found = false;
foreach($values as $key => $value) {
if ($value->id == 4) {
$found = true;
break;
}
}
if ($found) unset($values[$key]);
This is considered to be faster then any other solution since we only iterate the array to until we find the object we want to remove.
Note: You should not remove an element of an array while iterating so we do it afterwards here.
foreach($parentObj AS $key=>$element){
if ($element->id == THE_ID_YOU_ARE_LOOKING_FOR){
echo "Gottcha! The index is - ". $key;
}
}
$parentObj is obviously your root array - the one that holds all the others.
We use the foreach loop to iterate over each item and then test it's id property against what ever value you desire. Once we have that - the $key that we are on is the index you are looking for.
use array_search:
$a = new stdClass;
$b = new stdClass;
$a->id = 1;
$b->id = 2;
$arr = array($a, $b);
$index = array_search($b, $arr);
echo $index;
// prints out 1
try this
foreach($array AS $key=>$object){
if($object['id'] == 4){
$key_in_array = $key;
}
}
// chop it from the original array
array_slice($array, $key_in_array, 1);
Another way to achieve the result is to use array_filter.
$array = array(
(object)array('id' => 5),
(object)array('id' => 4),
(object)array('id' => 3)
);
$array = array_filter($array, function($item) {
return $item->id != 4;
});
print_r($array);
Here's my solution. Given, it is a bit hackish, but it will get the job done.
search(array $items, mixed $id[, &$key]);
Returns the item that was found by $id. If you add the variable $key it will give you the key of the item found.
function search($items, $id, &$key = null) {
foreach( $items as $item ) {
if( $item->id == $id ) {
$key = key($item);
return $item;
break;
}
}
return null;
}
Usage
$item = search($items, 4, $key);
unset($items[$key]);
Note: This could be modified to allow a custom key and return multiple items that share the same value.
I've created an example so you can see it in action.
A funny alternative
$getIdUnset = function($id) use ($myArray)
{
foreach($myArray as $key => $obj) {
if ($obj->id == $id) {
return $key;
}
}
return false;
};
if ($unset = $getIdUnset(4)) {
unset($myArray[$unset]);
}
Currently php does not have any supported function for this yet.
So refer to Java's Vector, or jQuery's $.inArray(), it would simply be:
public function indexOf($object, array $elementData) {
$elementCount = count($elementData);
for ($i = 0 ; $i < $elementCount ; $i++){
if ($object == $elementData[$i]) {
return $i;
}
}
return -1;
}
You can save this function as a core function for later.
In my case, this my array as $array
I was confused about this problem of my project, but some answer here helped me.
array(3) {
[0]=> float(-0.12459619130796)
[1]=> float(-0.64018439966448)
[2]=> float(0)
}
Then use if condition to stop looping
foreach($array as $key => $val){
if($key == 0){ //the key is 0
echo $key; //find the key
echo $val; //get the value
}
}
I know, after so many years this could be a useless answer, but why not?
This is my personal implementation of a possible index_of using the same code as other answers but let the programmer to choose when and how the check will be done, supporting also complex checks.
if (!function_exists('index_of'))
{
/**
* #param iterable $haystack
* #param callable $callback
* #param mixed|null &$item
* #return false|int|string
*/
function index_of($haystack, $callback, &$item = null)
{
foreach($haystack as $_key => $_item) {
if ($callback($_item, $_key) === true) {
$item = $_item;
return $_key;
}
}
return false;
}
}
foreach( $arr as $k=>&$a) {
if( $a['id'] == 4 )
unset($arr[$k]);
}
I've been trying unsuccessfully to write a recursive function to give me the depth of a given element. I just can't seem to get my head around the recursion. This is what I have, but it's not working correctly:
function getDepth($a, $e, $depth = 0) {
foreach ($a as $key => $val) {
if (is_array($val)) {
if ($key == $e) {
return $depth;
}
return getDepth($val, $e, $depth + 1);
}
else {
if ($val == $e) {
return $depth;
}
else {
return 1;
}
}
}
}
Can anyone please help point out what I'm doing wrong here? Thanks in advance for your help.
EDIT:
#Brad #Amber #Viktor Thanks, but this doesn't seem to be working either. Here's what I'm after... I have an array that looks like this:
[antonio] => Array
(
[ian] => Array
(
[molly] => Array
(
[blake] => blake
)
)
[shonda] => Array
(
[dana] => dana
[james] => james
)
[nels] => Array
(
[jason] => jason
[danny] => danny
)
[molly] => Array
(
[blake] => blake
)
[blake] => blake
[travis] => travis
)
It's a tree, and I'm hoping to find the depth level of a given name. So, I'll need to pass in a name, say blake. Then I'll want to traverse the whole tree keeping track of blake's depth whenever I find it as he could be (and indeed is in this example) in the tree at different levels. Assuming that the top-most depth level is 0, blake's level under antonio => ian => molly => blake is 3, but his level under antonio => blake is 1, so I would want to return 1. I will have to traverse the entire tree (luckily this function will not be called very often) to make sure that I've found the most shallow depth in the tree for the given user. Thanks again for your help.
Basically, to get the recursion right, if you know you have an array within your function, run your same function on it. We add the deepest path so far +1. In the end, you get what you are looking for.
function getDepth($a) {
$max=0;
foreach ($a as $val) {
if (is_array($val)) {
$tmp_depth=getDepth($val);
if ($max<($tmp_depth)) {
$max=$tmp_depth;
}
}
}
return $max+1;
}
I haven't benchmarked this or anything. Undoubtedly there could be speed improvements, if it is important.
function getDepth($a, $e, $depth = 0) {
$lower = false; // meaning 'not found'
// as you are looking for the less deep value, first check for values and then for arrays
// so there are chances when you do not traverse all the tree for a match
foreach ($a as $key => $val) if ($val == $e) return $depth;
foreach ($a as $key => $val) {
if (is_array($val)) {
$tmp = getDepth($val, $e, $depth + 1);
if($tmp) if ($lower === false || $tmp < $lower) $lower = $tmp;
}
}
return $lower;
}
$x=array(
antonio => Array(
ian => Array(
molly => Array(
blake => blake,
jhonyDeep => jhonyDeep
)
),
shonda => Array(
dana => dana,
james => james
),
nels => Array (
jason => jason,
danny => danny
),
molly => Array(
blake => blake
),
blake => blake,
travis => travis
)
);
echo getDepth($x, blake); // gives 1
echo getDepth($x, danny); // gives 2
echo getDepth($x, jhonyDeep); // gives 3
similar to my previous anwser but optimized for performance (and be careful, not tested)
function getDepth($a, $e, $depth = 0, $lower = false) {
// $lower = false means 'not found'
// as you are looking for the less deep value, first check for values and then for arrays
// so there are chances when you do not traverse all the tree for a match
foreach ($a as $key => $val) if ($val == $e) return $depth;
foreach ($a as $key => $val) {
if (is_array($val)) {
$tmp = false;
if($lower===false || $lower > $depth) $tmp = getDepth($val, $e, $depth + 1, $lower); // to do not recurse innecesary
if($tmp) {
if($tmp==$depth+1) return $tmp; //optimization: $depth+1 can't be beat by other values
if ($lower === false || $tmp < $lower) $lower = $tmp;
}
}
}
return $lower;
}
$x=array(
antonio => Array(
ian => Array(
molly => Array(
blake => blake,
jhonyDeep => jhonyDeep
)
),
shonda => Array(
dana => dana,
james => james
),
nels => Array (
jason => jason,
danny => danny
),
molly => Array(
blake => blake
),
blake => blake,
travis => travis
)
);
echo getDepth($x, blake); // gives 1
echo getDepth($x, danny); // gives 2
echo getDepth($x, jhonyDeep); // gives 3