Change multidimensional array value with wildcard in php?

Viewed 39

So say I have an array below. As an example, is it possible in PHP to replace the -2.7 value of the first array part to 100 without knowing the #RR key or #BR for the other part? Such as:

$array[8314][WILDCARD][-1] = 100;

Array
(
            [8314] => Array
                (
                    [#RR] => Array
                        (
                            [-1] => -2.7
                            [0] => 0
                        )

                )

            [8810] => Array
                (
                    [#BR] => Array
                        (
                            [-1] => 32500
                            [0] => 0
                        )

                )
)
2 Answers

I think that you are looking for the below solution using array_key_first:

$firstKey = array_key_first($array); //say we found 8314;
$WILDCARD = array_key_first($array[$firstKey]);

//replace the old value with 100;
$array[$firstKey][$WILDCARD][-1] = 100;

Yes:

foreach ($input as $outerKey => $outerValue) {
    foreach ($outerValue as $innerKey => $innerValue) {
         foreach ($innerValue as $key => $value) {
             if ($value === 2.7) $input[$outerKey][$innerKey][$key] = 100;
         }
    }
}

The code above assumes that you want to change 2.7 => 100 for all elements. If, instead of that you need to do it just for the first, then:

    $visited = false;
    foreach ($outerValue as $innerKey => $innerValue) {
         if ($visited) break;
         $visited = true;
         foreach ($innerValue as $key => $value) {
             if ($value === 2.7) $input[$outerKey][$innerKey][$key] = 100;
         }
    }
Related