简体   繁体   中英

Search an element in associative array in php

I have this array....

Array ( 
    [0] => 72 
    [1] => 73 
    [2] => 74 
)

and i want to search these elements in multidimensional array which is given below.. and i want to compare with just "lead_image_id" as above array is actually array of "lead_image_id"

 Array 
 (
    [0] => stdClass Object (
        [lead_image_id] => 60
        [lead_image_name] => assets/images/logo.png
        [lead_image_lead_id] => 74
        [lead_image_status] => 0
    )
    [1] => stdClass Object (
        [lead_image_id] => 69
        [lead_image_name] => uploads/leads/5276.png
        [lead_image_lead_id] => 74
        [lead_image_status] => 0
    )
    [2] => stdClass Object (
        [lead_image_id] => 70
        [lead_image_name] => assets/images/logo.png
        [lead_image_lead_id] => 74
        [lead_image_status] => 0
    )
)

You can do this like now. There is 2 array firstarr is your first array and secarr is second associative array.

foreach($secarr as $secval){
    foreach($secaval as $val){
        if($val['lead_image_lead_id'] == $firstarr['value']){
            echo "match";
        }else{
            echo "not matched";
        }
    }
}

you need use two loops:

$source = [
          [
              'lead_image_id' => 60 ,
              'lead_image_name' => 'assets/images/logo.png ',
              'lead_image_lead_id' => 74 ,
              'lead_image_status' => 0
          ]
   ];

$searches = [72, 73, 74];

$result = [];

foreach($source as $value) {
    foreach($searches as $search) {
        if($value->lead_image_lead_id == $search) {
            $result[] = $value;
        }
    }
}    

var_dump($result);

or use array_search :

foreach($source as $value) {
    $r = array_search($value['lead_image_lead_id'], $searches);
    if($r !== false) {
        $result[] = $value;
    }
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM