Php阵列。 环。 如果条件为真,则设置变量。 再循环。 需要重复一遍。 但不重复相同的代码

Here is longer example https://eval.in/392036

Loop through array.

If array value == to certain (first) variable[0] , then set next variable[1].

And again loop through the same array (a loop inside loop).

And again check if array value == the next variable[1] .... and again do the same.

So manually copy/paste the same code, just change variable[x].

Have such array

(
[0] => Array
    (
        [Id] => 17
        [Value] => ProductsParentId_0_CurrentId_17
        [ParentId] => 0
    )

[1] => Array
    (
        [Id] => 1
        [Value] => HomeParentId_0_CurrentId_1
        [ParentId] => 0
    )

[2] => Array
    (
        [Id] => 18
        [Value] => ComputersParentId_17_CurrentId_18
        [ParentId] => 17
    )

.....

)

And loop through

foreach ( $arr as $k_arr => $v_arr ){

if( $v_arr['ParentId'] == 0 ){
echo $v_arr['Value']. "
";
$parent_id_for_current[1] = $v_arr['Id'];

    foreach ( $arr as $k_arr => $v_arr ){
    if( $v_arr['ParentId'] == $parent_id_for_current[1] ){
    echo $v_arr['Value']. "
";
    $parent_id_for_current[2] = $v_arr['Id'];

        foreach ( $arr as $k_arr => $v_arr ){
        if( $v_arr['ParentId'] == $parent_id_for_current[2] ){
        echo $v_arr['Value']. "
";
        $parent_id_for_current[3] = $v_arr['Id'];

            .....

        }//if( $v_arr['ParentId'] == $parent_id_for_current[2] )
        }//foreach

    }//if( $v_arr['ParentId'] == $parent_id_for_current[1] )
    }//foreach

}//if( $v_arr['ParentId'] == $parent_id_for_current[0] )


}//foreach ( $arr as $k_arr => $v_arr )

Is it possible to get the same result, not repeating (copy/paste) foreach, if

Expected outcome is:

1) show ['Value'] where [ParentId] => 0

1.1) define variable with value [Id] => 17

2) loop again, find and show ['Value'] where [ParentId] == variable defined in 1.1). And repeat all. Again define another variable, then again loop, check if some [ParentId] equals to the defined variable... like in the link at top of question

It looks like you have a recursive pattern:

function loopMyArray(&$array, &$parent, $i)
{
    // That's your stop condition of the recursive pattern
    // I think it's what you want.
    if (count($array) == $i)
    {
        return;
    }
    // The foreach loop call the "loopMyArray" at each iteration
    foreach ($array as $k_arr => $v_arr)
    {
        if( $v_arr['ParentId'] == $parent[$i])
        {
            echo $v_arr['Value']. "
";
            $parent[$i+1] = $v_arr['Id'];
            loopMyArray($array, $parent, $i+1);
        }
    }
}

$array = [...]
$parent = [0]
loopMyArray($array, $parent, 0);