Checking if array value exists in a PHP multidimensional array

后端 未结 3 343
天命终不由人
天命终不由人 2021-01-15 03:09

I have the following multidimensional array:

Array ( [0] => Array 
         ( [id] => 1 
           [name] => Jonah 
           [points] => 27 )
         


        
相关标签:
3条回答
  • 2021-01-15 03:42

    What about looping over your array, checking for each item if it's id is the one you're looking for ?

    $found = false;
    foreach ($your_array as $key => $data) {
        if ($data['id'] == $the_id_youre_lloking_for) {
            // The item has been found => add the new points to the existing ones
            $data['points'] += $the_number_of_points;
            $found = true;
            break; // no need to loop anymore, as we have found the item => exit the loop
        }
    }
    
    if ($found === false) {
        // The id you were looking for has not been found, 
        // which means the corresponding item is not already present in your array
        // => Add a new item to the array
    }
    
    0 讨论(0)
  • 2021-01-15 03:52

    you can first store the array with index equal to the id. for example :

     $arr =Array ( [0] => Array 
         ( [id] => 1 
           [name] => Jonah 
           [points] => 27 )
        [1] => Array 
         ( [id] => 2 
           [name] => Mark 
           [points] => 34 )
      );
     $new = array();
     foreach($arr as $value){
        $new[$value['id']] = $value; 
     }
    
    //So now you can check the array $new for if the key exists already 
    if(array_key_exists(1, $new)){
        $new[1]['points'] = 32;
    }
    
    0 讨论(0)
  • 2021-01-15 04:03

    Even though the question is answered, I wanted to post my answer. Might come handy to future viewers. You can create new array from this array with filter then from there you can check if value exist on that array or not. You can follow below code. Sample

    $arr = array(
            0 =>array(
                    "id"=> 1,
                    "name"=> "Bangladesh",
                    "action"=> "27"
                ),
             1 =>array(
                    "id"=> 2,
                    "name"=> "Entertainment",
                    "action"=> "34"
                     )
            );
    
         $new = array();
         foreach($arr as $value){
            $new[$value['id']] = $value; 
         }
    
    
        if(array_key_exists(1, $new)){
            echo $new[1]['id'];
        }
        else {
          echo "aaa";
        }
        //print_r($new);
    
    0 讨论(0)
提交回复
热议问题