Borja Borja - 4 months ago 8
PHP Question

Replacing inner keys from multidimensional array in PHP

Having the following array:

array(4) {
[0]=>
array(2) {
[0]=>
string(3) "233"
[1]=>
string(37) "some data"
}
[1]=>
array(2) {
[0]=>
string(3) "233"
[1]=>
string(68) "some other data"
}
[2]=>
array(2) {
[0]=>
string(3) "144"
[1]=>
string(38) "some other data"
}
[3]=>
array(2) {
[0]=>
string(3) "233"
[1]=>
string(42) "some other data"
}
}


I want to replace the values
233
and
144
(the key
0
from the inner array) by some random HEX color. The ones with the same keys (
233
) for example, has to have the same HEX color (
FFF000
for example in the desired solution above).

This is the function I use to generate random HEX colors:

function randHEXcolor() {
return sprintf('%06X', mt_rand(0, 0xFFFFFF));
}


My desired output should be:

array(4) {
[0]=>
array(2) {
[0]=>
string(6) "FFF000"
[1]=>
string(37) "some data"
}
[1]=>
array(2) {
[0]=>
string(6) "FFF000"
[1]=>
string(68) "some other data"
}
[2]=>
array(2) {
[0]=>
string(6) "111333"
[1]=>
string(38) "some other data"
}
[3]=>
array(2) {
[0]=>
string(6) "FFF000"
[1]=>
string(42) "some other data"
}
}


How can I archieve this?

Thanks in advance.

Answer
foreach ($array as &$item) {
    if (!isset($temp[$item[0]]) {
        $temp[$item[0]] = randHEXcolor();
    }
    $item[0] = $temp[$item[0]];
}
Comments