如果汽车数组中的数组的第3个元素为真,我想将其他元素设置为真。如何实现呢?
<?php
$cars = array
(
array(1,1,'f'),
array(2,2,'f'),
array(3,3,'t'),
array(4,4,'f')
);
foreach($cars as $keys){
if($keys[2]=='t')
$count=1;
}
foreach($cars as $keys){
if($count==1)
$keys[2] = 't';
}
print_r($cars);
?>
答案 0 :(得分:1)
如下所述,只需更改2件事,请尝试:
$cars = array
(
array(1,1,'f'),
array(2,2,'f'),
array(3,3,'t'),
array(4,4,'f')
);
$count = 0; // declare $count
foreach($cars as $keys){
if($keys[2]=='t')
$count=1;
}
foreach($cars as $key=>$keys){
if($count==1)
$cars[$key][2] = 't'; // change value to t like this
}
输出:
Array
(
[0] => Array
(
[0] => 1
[1] => 1
[2] => t
)
[1] => Array
(
[0] => 2
[1] => 2
[2] => t
)
[2] => Array
(
[0] => 3
[1] => 3
[2] => t
)
[3] => Array
(
[0] => 4
[1] => 4
[2] => t
)
)
答案 1 :(得分:1)
你几乎接近,只需进行此更改,使用参考符号&
进行实际更改
来自
foreach($cars as $keys){
到
foreach($cars as &$keys){
答案 2 :(得分:1)
$exists= false;
foreach($cars as $car)
{
if($car[2] == 't')
{
$exists= true;
}
}
if($exists)
{
for($i=0; $i<count($cars); $i++)
{
$cars[$i][2] = 't';
}
}
答案 3 :(得分:0)
以下是您的解决方案
<?php
$cars = array(
array(1,1,'f'),
array(2,2,'f'),
array(3,3,'t'),
array(4,4,'f')
);
if(in_array('t', array_column($cars, 2))){
$cars = array_map(function($v){
$v[2] = 't';
return $v;
}, $cars);
}