Home > other >  how to get all the array values related to key and values in php array
how to get all the array values related to key and values in php array

Time:11-19

I have the following array

Array
(
    [22] => Array
        (
            [0] => 1074
            [1] => 1926
        )

    [1772] => Array
        (
            [0] => 1080
            [1] => 1921
        )

    [1926] => Array
        (
            [0] => 1772
        )

    [1080] => Array
        (
            [0] => 1833
        )
)

I want all the data related to key 1926. Here in above 1926 has value 1772 then in this key has 2 values 1080 and 1921 I have to check both keys and so on.

The result I want: array(

[0]=>1772
[1]=>1080
[2]=>1921
[3]=>1833
.....

)

I have tried many solutions, but I am not getting desired response, I have created the below code that returns me only one value 1772

function arrayTraverse($targetKey, $array, $returndata=[]) 
{
    foreach($array as $key=>$values){
        if($targetKey == $key){
            unset($array[$targetKey]);
            if(is_array($values))
            {
                foreach($values as $val){
                    $returndata = array_merge($returndata, array($val));
                    arrayTraverse($val, $array, $returndata);
                }
            }
        }
    }
    return $returndata;
}

Here at last I am getting only [0]=>1772

CodePudding user response:

foreach array
  foreach subArray 
     if isset(array[value])
       subArray[key] &= array[value] 

CodePudding user response:

I solve the above mine problem, below is the code that will get the exact data

function arrayTraverse($reportingusersArr, $targetkey, $resultarr=[], $checkvalues=[]){
    $uservalues = $reportingusersArr[$targetkey];
    if($uservalues){
        unset($reportingusersArr[$targetkey]);
        $resultarr[$targetkey] = $uservalues;
        $lastResultvalue = $uservalues;
        foreach($uservalues as $keya=>$uva){
            $checkvalues[] = $uva;
        }

        foreach($uservalues as $key=>$uv){
            $elementkey = array_search($targetkey, $checkvalues);
            unset($checkvalues[$elementkey]);
            return arrayTraverse($reportingusersArr, $uv, $resultarr, $checkvalues);
        }
    }
    else{
        $othercheckval = $checkvalues;
        foreach($checkvalues as $key3=>$uv2){
            $elementkey = array_search($uv2, $othercheckval);
            unset($othercheckval[$elementkey]);
            return arrayTraverse($reportingusersArr, $uv2, $resultarr, $othercheckval);
        }
    }
    $finalarray = [];
    foreach($resultarr as $fkey=>$fvaluearr){
        foreach($fvaluearr as $fval)
        {
            $finalarray[] = $fval;
        }
    }
    return $finalarray;
}
  • Related