用文本标签替换PHP数组?
如果值=1,您认为替换以下数组项的最佳方法是什么 我的PHP用文本标签替换PHP数组?,php,arrays,Php,Arrays,如果值=1,您认为替换以下数组项的最佳方法是什么 我的PHP $tags = array( 'checkbox_1' => $post['custom_fields']['checkbox_1'][0], 'checkbox_2' => $post['custom_fields']['checkbox_2'][0], 'checkbox_3' => $post['custom_fields']['checkbox_3'][0], 'checkbo
$tags = array(
'checkbox_1' => $post['custom_fields']['checkbox_1'][0],
'checkbox_2' => $post['custom_fields']['checkbox_2'][0],
'checkbox_3' => $post['custom_fields']['checkbox_3'][0],
'checkbox_4' => $post['custom_fields']['checkbox_4'][0],
'checkbox_5' => $post['custom_fields']['checkbox_5'][0],
'checkbox_6' => $post['custom_fields']['checkbox_6'][0],
'checkbox_7' => $post['custom_fields']['checkbox_7'][0],
'checkbox_8' => $post['custom_fields']['checkbox_8'][0]
);
我的阵列
Array
(
[checkbox_1] => 1
[checkbox_2] => 0
[checkbox_3] => 0
[checkbox_4] => 0
[checkbox_5] => 0
[checkbox_6] => 0
[checkbox_7] => 0
[checkbox_8] => 0
)
我是否需要修改数组映射以给每个数组添加一个标签,并且仅当值为1时才输出?是的,数组映射对您有好处:
$array1 = array(
'checkbox_1' => 1,
'checkbox_2' => 0,
'checkbox_3' => 0,
'checkbox_4' => 0,
'checkbox_5' => 0,
'checkbox_6' => 0,
'checkbox_7' => 0,
'checkbox_8' => 0
);
function label($val) {
if ($val === 1) {
return 'Checked';
}
return 0;
}
$array2 = array_map('label', $array1);
var_dump($array2);
输出为:
array
'checkbox_1' => string 'Checked' (length=7)
'checkbox_2' => int 0
'checkbox_3' => int 0
'checkbox_4' => int 0
'checkbox_5' => int 0
'checkbox_6' => int 0
'checkbox_8' => int 0
只需使用
数组映射()
。例如:
$post = [
'custom_fields'=>[
'checkbox_1'=>[
1, 5, 8, 6
],
'checkbox_2'=>[
0, 5, 8, 6
],
'checkbox_3'=>[
7, 3, 2, 1
],
]
];
$result = array_map(function($v){
$val = ($v[0] == 1) ? 1 : 0;
return $val;
}, $post['custom_fields']);
输出:
Array
(
[checkbox_1] => 1
[checkbox_2] => 0
[checkbox_3] => 0
)
您需要转换:
Array([checkbox\u 1]=>1[checkbox\u 2]=>0[checkbox\u 3]=>0[checkbox\u 5]=>0[checkbox\u 6]=>0[checkbox\u 7]=>0[checkbox\u 8]=>0)
到:Array([checkbox\u 1]=>Ok'[checkbox\u 2]=>0[checkbox\u 3]=>0[checkbox\u 4]=>0[checkbox\u 5]=>0[复选框\u 6]=>0[复选框\u 7]=>0[复选框\u 8]=>0)
?要更改数组还是仅输出?为什么不干脆` foreach($MyArray as$key=>$value){if($value>=1){echo“key是:“..$key.”,value是:“..$value.””;}}}。如果您可以像使用
$post['custom_fields']['checkbox']=[1,0,0,0,…]
这样发布,那就更好了。