用文本标签替换PHP数组?

时间:2014-11-17 16:08:23

标签: 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],
    '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
)

我是否需要修改Array Map以给每个人一个标签,并且只有在值为1时才输出?

2 个答案:

答案 0 :(得分:0)

是的,阵列图对你有好处:

$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

答案 1 :(得分:0)

只需使用array_map()即可。例如:

$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
)
相关问题