从所需的键填充变量

时间:2015-01-19 20:50:52

标签: php

$data变量通过$personalDetailsRequiredFields从所需的密钥填充。下面的代码确实有效,但有更短的方法吗?

   $personalDetailsRequiredFields = [
        'contact_title',
        'contact_first_name',
        'contact_last_name',
        'contact_phone_number',
        'contact_mobile_number',
        'contact_email',
    ];
    $personalDetails = SessionOrder::getPersonalDetails();

    foreach($personalDetails as $key => $value) {
        if (in_array($key,$personalDetailsRequiredFields)) {
            $data['personalDetails'][$key] = $value;
        }
    }

    echo "<pre>";
    print_r($data);
    echo "</pre>";

1 个答案:

答案 0 :(得分:1)

$data['personalDetails'] = array_intersect_key(
    $personalDetails, 
    array_flip($personalDetailsRequiredFields)
);

应该给你你想要的东西,而不需要循环和测试