移除另一个数组中不存在的数组的键


Remove Key of One Array of Not Have in Other Array

我必须删除一个数组的键数组中不存在的元素,比如

    /**
     * I Have This Array, With Keys
     * Name, Lastname, Date
     */
    $Array = Array( 'name' => 'Mike', 'lastname' => 'Griggs', 'date' => strftime( '%A %c' ) );
    /**
     * And The Split , Make This One Array
     */
    $Fields = 'name, lastname';
    foreach( split( ',', str_replace( ' ', NULL, $Fields ) ) as $Index => $Field ):
             if(!array_key_exists( $Field, split( ',', str_replace( ' ', NULL, $Fields )))):
                   unset( $Array[$Field] );
             endif;
    endforeach;
    print_r( $Array );
    /**
     * i Have to Remove The Elements of $Array
     * That Not Have in $Fields, In This Case, Unset 'date' From $array
     */

但是在数组中重新定义日期字段我需要从数组中取消$Fields中没有的键,如果数组中没有Name,只返回LastName .

谢谢[]的

你应该考虑用合适的英语来提问。主要是因为用户要么批评它而不是回答它,要么完全忽略它。

话虽这么说,我假设您有一个数组和一个以逗号分隔索引的字符串。然后你想通过删除额外的数据来"净化"你的数组。

下面是一个关于如何做到这一点的例子:

<?php
$array = Array( 'name' => 'Mike', 'lastname' => 'Griggs', 'date' => strftime( '%A %c' ) );
$fields = 'name, lastname';
function removeIndex($a,$f){
    $f=explode(',',$f);
    $b=array();
    foreach($f as $v){
        $v=trim($v);// only need if you have extra whitespace
        $b[$v]=$a[$v];
    }
    return $b;
}
$array=removeIndex($array,$fields);
print_r($array);
?>