开发者

How to use foreach to verify value in a 3-dimensional array without having duplicated output in php?

开发者 https://www.devze.com 2023-02-05 04:55 出处:网络
Hi my question is a little tricky, I got a 3-dimensional array and try to verify the 3rd level value and echo both 1st and 3rd level values.

Hi my question is a little tricky, I got a 3-dimensional array and try to verify the 3rd level value and echo both 1st and 3rd level values. The following is the cod开发者_Python百科e example, and my failed approaches.

$myArray=array(
"mySub0" => arrary(
  0 => array("mySubSub0" => "1","mySubSub1" => "a"),
  1 => array("mySubSub0" => "2","mySubSub1" => "b"),
  2 => array("mySubSub0" => "3","mySubSub1" => "b"),
 ),
 "mySub1" => arrary(
  0 => array("mySubSub0" => "4","mySubSub1" => "a"),
  1 => array("mySubSub0" => "5","mySubSub1" => "a"),
  2 => array("mySubSub0" => "6","mySubSub1" => "a"),
 ),
 "mySub2" => arrary(
  0 => array("mySubSub0" => "7","mySubSub1" => "a"),
  1 => array("mySubSub0" => "8","mySubSub1" => "b"),
  2 => array("mySubSub0" => "9","mySubSub1" => "a"),
 ),
),

I want to check if the value of "mySubSub1" is b. if yes, echo the value of "mySubSub0" and the related key in first-level of the array. It should be like this:

mySub0
2
3
mySub2
8

My failed approach is

 foreach ($myArray as $a => $b)
 {
 foreach ($b as $c)
 if($c[mySubSub1]=="b")
    {
        echo $a
        echo $c[mySubSub0];
    }
 else {
    }
 }

The result will have one duplicate mySub0

 mySub0
 2
 mySub0
 3
 mySub2
 8

if I move the "echo $a" out of the "if"

foreach ($myArray as $a => $b)
 {
 echo $a
 foreach ($b as $c)
 if($c[mySubSub1]=="b")
        {
        echo $c[mySubSub0];
    }
 else {
    }
 } 

the result would be

 mySub0
 2
 3
 mySub1
 mySub2
 8

one unwanted "mySub1" because there is no place to verify if there is a value b.

It has bothered my a lot today. I tried to Google but haven't found the right answer. Really hope someone can help me. Thank you in advance


Here's something that should work:

function find_value($arr, $key, $value, $sibling)
{
    foreach ($arr as $k => $v)
    {
        $results = _find_value($v, $key, $value, $sibling);
        if (count($results) > 0) {
            echo $k;
            foreach ($results as $result) {
                echo $result;
            }
        }
    }
}

function _find_value($arr, $key, $value, $sibling)
{
    $out = array();
    foreach ($arr as $k => $v)
    {
        if ($v[$key] == $value)
            $out[] = $v[$sibling];
    }
    return $out;
}

find_value($myArray, "mySubSub1", "b", "mySubSub0");

Basically, the main function loops over items in the outer array, calling the inner function to get a list of the "sibling" keys where the main key matches the value you're looking for. If a non-zero number of results are obtained in the inner function, echo and loop.

Hopefully this does the trick for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消