简体   繁体   中英

Distinct values from an object property within an array?

I'm making an array with an object inside of it and I need to check when looping and adding whether the object property name already has a duplicate value and then add only distinct results to the array.

$lifestyle = array();    
foreach ($this->images as $image) {
    if(!in_array($image->getName(), $lifestyle['name'])){
       $lifestyle[] = $image;
    }
}

But the $lifestyle['name'] on line 3, obviously isn't targeting the object, but I'm not really sure how to do this! I just keep running into one error or another.

The array/object that is made when I don't try and filter out duplicates looks like this:

array (size=3)
0 => 
object(Pingu\ProductBundle\Entity\Image)[746]
  private 'id' => int 1175
  private 'name' => string 'cl0021_02' (length=9)
  private 'main' => boolean false
  private 'active' => boolean true
  private 'type' => string 'lifestyle' (length=9)
1 => 
object(Pingu\ProductBundle\Entity\Image)[747]
  private 'id' => int 1176
  private 'name' => string 'cl0021_02' (length=9)
  private 'main' => boolean false
  private 'active' => boolean true
  private 'type' => string 'lifestyle' (length=9)
2 => 
object(Pingu\ProductBundle\Entity\Image)[748]
  private 'id' => int 1177
  private 'name' => string 'cl0021_02' (length=9)
  private 'main' => boolean false
  private 'active' => boolean true
  private 'type' => string 'lifestyle' (length=9)

Your code is in fact wrong around the $lifestyle['name'] part, as you pointed out.

in_array function expects an array as second argument, but you try to set it with $lifestyle['name'] , which is not correct (and doesn't exist).

Your $lifestyle var is an indexed array, in which you add the images (line 4).

If you want to check whether a given property value exists in the array of images objects, you can't do that with in_array ( in_array is used with statements like that : in_array(10, [1,2,3]); // evaluates to FALSE .

You have to loop through the entire $lifestyle array and check for each item it's name property :

$lifestyle = array();    
foreach ($this->images as $image)
{
    $found = false;
    foreach ( $lifestyle as $item )    
        if ( $item->name == $image->getName() )
        {
            $found = true;
            break; // don't bother to continue $lifestyle loop, item is duplicate
        }

    // check if previous loop found something
    if ( !$found )
        $lifestyle[] = $image;
}

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