数组未定义偏移量与PHP

时间:2017-02-25 15:02:10

标签: php arrays

<?php

$ar = Array (

     [0] => Array ( [id] => 1 [social_id] => [role_id] => 0 [name] => [first_name] => Jimmy [last_name] => rathore [gender] => male [dob] => 06-02-1992 [language] => english [location] => xyz [address] => xyz [email] => xyz@xyz.com [phone] => 9876543210 )


     [1] => Array ( [id] => 3 [social_id] => [role_id] => 0 [name] => [first_name] => Dev [last_name] => Smith [gender] => [dob] => [language] => [location] => xyz [address] => xyz [email] => yyy@sds.com [phone] => 7838344344 )

      [2] => Array ( [id] => 4 [social_id] => [role_id] => 0 [name] => [first_name] => Col [last_name] => Manon [gender] => male [dob] => 02-02-2017 [language] => english [location] => London [address] => ABCD [email] => londs@an.com [phone] => 7894561230)
       ) ;


$array = Array (

     [0] => Array ( [id] => 1 [sm_id] => 1 [field_name] => first_name [value] => G2 [created_at] => 2017-02-24 11:05:03 [updated_at] => 2017-02-24 11:05:03 [deleted_at] => )
 );

$arr = array();

foreach($row=0; $row<count($ar); $row++){
    foreach($col=0; $col<count($array); $col++){
        if($ar['0']['id'] == $array['0']['id']){
            $arr['first_name'] = $ar['0']['first_name'];
            $arr['last_name'] = $ar['0']['last_name'];
            $arr['email'] = $ar['0']['email'];
            $arr['phone'] = $ar['0']['phone'];
        }
    }
}

print_r($arr);die;

?>

我希望基于$ ar ['0] ['id']的$ array ['0'] ['sm_id']

如果$ ar的id与$ array的sm_id匹配推送到一个数组,其值如何实现相同。请建议

Expected result

Array( [id] => 1 [first_name] => Jimmy [last_name] => rathore [gender] => male [dob] => 06-02-1992 [language] => english [location] => xyz [address] => xyz [email] => xyz@xyz.com [phone] => 9876543210 );

1 个答案:

答案 0 :(得分:1)

如果原始数组为$ar,且sm_id值为$array的数组:

,则可以这样做
// Create a hash of all sm_id values to be found
$ids = array_flip(array_column($array, "sm_id"));

// filter the original array to get only those with an id value in that hash
$arr = array_filter($ar, function ($row) use ($ids) {
    return isset($ids[$row["id"]]);
});

print_r ($arr);