我有两个数组,一个数组包含所有有效字段,第二个数组是我要解析的数据数组。我想删除数据数组中没有用有效字段数组映射的任何无效字段: / p>
有效字段数组:
$valid_fields = array(
"first_name",
"last_name",
"uid",
"email",
"address" => array(
"mailing" => array("building_no", "street", "city", "zip", "country"),
"billing" => array("building_no", "street", "city", "zip", "country"),
"home" => array("building_no", "street", "city", "zip", "country"),
"work" => array("building_no", "street", "city", "zip", "country")
),
"home_address",
"home_address",
"billing_address",
"dob",
"gender",
"occupation",
"ip",
"site_id",
"date_created",
"social_network_ids" => array("facebook",
"twitter",
"pintreast",
"myspace",
"skype"),
"occupations" => array("current", "past" => array()),
"education", "income", "country", "city", "longitude", "latitude");
数据阵列:
$data = array(
"first_name" => "FFF",
"last_name" => "LLL",
"uid" => "12345", "email" => "aaa@f.com",
"address" => array(
"mailing" => array("building_no" => "BBAA", "street" => "BBSS", "city" => "BBCC")
),
"social_network_ids" => array(
"facebook" => "fbid",
"twitter" => "twitter",
),
"occupations" => array("current", "past" => array(), "yolo" => "tttt"),
);
我的解析功能:
function parse_array($parms, $valid_fields) {
$result = array();
foreach ($valid_fields as $valid_field) {
if (is_array($parms[$valid_field])) {
$result[$valid_field] = parse_array($parms[$valid_field], $valid_field);
} else {
if (isset($parms[$valid_field]) && $parms[$valid_field] != "") {
$result[$valid_field] = $parms[$valid_field];
}
}
}
return $result;
}
我称之为它给了我这个显然无效的数组:
Array
(
[first_name] => FFF
[last_name] => LLL
[uid] => 12345
[email] => aaa@f.com
)
答案 0 :(得分:3)
在你的PHP函数中,你使用$ valid_field作为索引从$ data数组中获取项目,但有时$ valid_field可以是一个数组本身,试试这种方法:
function parse_array($parms, $valid_fields) {
$result = array();
foreach ($valid_fields as $k => $valid_field) {
$key = $valid_field;
if (is_array($valid_field)) {
$key = $k;
}
if (isset($parms[$key])) {
if (is_array($parms[$key])) {
$result[$key] = parse_array($parms[$key], $valid_field);
} else {
if (isset($parms[$key]) && $parms[$valid_field] != "") {
$result[$key] = $parms[$valid_field];
}
}
}
}
return $result;
}