Php 如果满足条件,则在数组上添加额外的键和值
代码: 如果阵列上有一个Php 如果满足条件,则在数组上添加额外的键和值,php,arrays,Php,Arrays,代码: 如果阵列上有一个status=sent,如何在所有阵列上添加$value['dupe']=1 预期结果: $arr = array(); foreach ($res as $key => $value) { if($value['status'] == 'sent'){ $arr[] = array($value, $value['dupe'] = 1); } } 此代码可能对您有所帮助 Array(
status=sent
,如何在所有阵列上添加$value['dupe']=1
预期结果:
$arr = array();
foreach ($res as $key => $value) {
if($value['status'] == 'sent'){
$arr[] = array($value, $value['dupe'] = 1);
}
}
此代码可能对您有所帮助
Array(
Array(
[name] => John
[last] => Smith
[status] => sent
[dupe] => 1
)
Array(
[name] => Jane
[last] => Doe
[status] => pending
[dupe] => 1
)
Array(
[name] => Kripky
[last] => Woe
[status] => pending
[dupe] => 1
)
)
此循环应该为您完成以下操作:
// first, define a function that tells if there is a statut = sent
function statut_exist($arr)
{
foreach ($arr as $value)
if($value['status'] == 'sent')
return true;
return false;
}
// then add the dupe if there is a statut = sent
if(statut_exist())
foreach ($res as $value)
$value['dupe'] = 1
注意:这使用了引用变量(
&
),因此它将更新实际数组。效果很好!非常感谢。
// first, define a function that tells if there is a statut = sent
function statut_exist($arr)
{
foreach ($arr as $value)
if($value['status'] == 'sent')
return true;
return false;
}
// then add the dupe if there is a statut = sent
if(statut_exist())
foreach ($res as $value)
$value['dupe'] = 1
foreach ($a as $i) {
if ($i['status'] == 'sent') {
foreach ($a as &$_i) {
$_i['dupe'] = 1;
}
}
}