从数组php获取set元素

时间:2014-06-06 18:06:32

标签: php arrays

我在php中有数组:

Array
    (
        [id] => 1
        [comp_id] => 1
        [transaction_purpose] => 0
        [source_of_funds] => 1
        [beneficiary_relationship] => 0
        [cus_occupation] => 0
        [cus_id_image_2] => 0
        [cus_id_image_3] => 0
        [ben_id_type] => 0
        [ben_id_number] => 1
    )

如果valie为1,我想只得到数组键=>值对。

结果数组应为:

Array
    (
        [id] => 1
        [comp_id] => 1
        [source_of_funds] => 1
        [ben_id_number] => 1
    )

我尝试过:

$returnArray = array();
    foreach($mainArray as $r){
        if($r>0){
            array_push($returnArray, $mainArray);
        }
    }

但是,它给了我4次主阵列。有没有办法实现这个目标?感谢..

3 个答案:

答案 0 :(得分:5)

只需使用array_filter()

$newarray = array_filter($array, function($var) { return ($var === 1); });

$newarray = array_filter($array);

Demo

$array = array(
    'id' => 1,
    'comp_id' => 1,
    'transaction_purpose' => 0,
    'source_of_funds' => 1,
    'beneficiary_relationship' => 0,
    'cus_occupation' => 0,
    'cus_id_image_2' => 0,
    'cus_id_image_3' => 0,
    'ben_id_type' => 0,
    'ben_id_number' => 1
);

$newarray = array_filter($array);

print_r($newarray);

Array
(
    [id] => 1
    [comp_id] => 1
    [source_of_funds] => 1
    [ben_id_number] => 1
)

答案 1 :(得分:3)

试试这个:

$returnArray = array_filter($result);

您可以查看PHP的array_filter功能以获取更多信息。

答案 2 :(得分:0)

那么,你还有什么期望呢?

        array_push($returnArray, $mainArray);

如果您找到一个值> 0的元素,则将整个原始数组推送到新数组,而不仅仅是您刚测试的键/值。

你可能想要:

$newarr = array();
foreach($mainArray as $key => $value) {
   if ($value > 0) {
        $newarr[$key] = $value;
   }
}