Aryan Aryan - 4 months ago 28
PHP Question

Set inner value for multidimensional array

What I want is that if I have

array('B2WGUR0276 ','TMT Steel')
and once its last value is true then set its last value to be true for all the same combinations of
('B2WGUR0276 ','TMT Steel')
.

$for_quantity sets true or false for the 3rd element in inner array

<?php
$b=array
(array('B2WGUR0276 ','TMT Steel','10','false'),
array('B2WGUR0276','TMT Steel','5','true'),
array('B2WGUR0276','Jindal JSW ','10','false'),
array('B2WGUR0276 ','TMT Steel','10','false')
);
$f=array(array('B2WGUR0276 ','TMT Steel'),array('B2WGUR0276','Jindal JSW '),array('B2WGUR0276 ','TMT Steel'));
foreach($b as $key=>$keys) {
if($for_quantity=='true'&&in_array($f,$b)) {
$b[$key][3]='true';
}
}

?>


output that is updated array $b should look like:

$b=array
(array('B2WGUR0276 ','TMT Steel','10','true'),
array('B2WGUR0276','TMT Steel','5','true'),
array('B2WGUR0276','Jindal JSW ','10','false'),
array('B2WGUR0276 ','TMT Steel','10','true')
);

Answer

Given the array $b, you could use this:

$match = array_flip(array_map(function ($row) {
    return end($row) === 'true' ? $row[0] . "|" . $row[1] : "";
}, $b));
foreach ($b as &$row) { 
    $row[count($row)-1] = isset($match[$row[0] . "|" . $row[1]]) ? 'true' : 'false';
}

After this code $b will be as you want it to be.

See it run on eval.in.

Comments