2

i'm trying to build an array from an Object in PHP. I only want certain properties from the object but I don;t know what they will be each time. The names of the properties I need are stored in an array. Here is how my code works currently:

// Hard-coded attributes 'colour' and 'size'

while ($objVariants->next())
{   
    $arrVariants[] = array
    (   
        'pid' => $objVariants->pid,
        'size' => $objVariants->size,
        'colour' => $objVariants->colour,
        'price' => $objVariants->price                                                      
    );        
}

Instead of hard coding the attributes (colour and size) I want to use variables, this is because it may not always be colour and size depending on what the user has set in the CMS. For example:

$arrVariantAttr = $this->getVariantAttr(); // Get the names of the custom variants and put them in an array e.g colour, size

while ($objVariants->next())
{   
    $arrVariants[] = array
    (   
        'pid' => $objVariants->pid,

        foreach($arrVariantAttr as $attr)
        {
            $attr['name'] => $objVariants-> . $attr['name']; // Get each variant out of the object and put into an array
        }

        'price' => $objVariants->price                                                      
    );        
}

The above code doesn't work, but hopefully it illustrates what i'm trying to do. Any help would be appreciated, thank you!

4 Answers 4

2

You could use get_object_vars() to get all variables of an object:

$arrVariants[] = get_object_vars($objVariants);

In order to exclude specific properties from the object you could do like this:

$arrVariants = get_object_vars($objVariants);
// array containing object properties to exclude
$exclude = array('name');
// walk over array and unset keys located in the exclude array
array_walk($arrVariants, function($val,$key) use(&$arrVariants, $exclude) {
    if(in_array($key, $exclude)) {
        unset($arrVariants[$key]);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Useful to know about, but in this case I only want specific properties. The Object contains other ones I don't need.
@JamieDevine - I added code to remove specific variables from the array returned from get_objects_vars().
1

You could create an array in the object containing the attributes:

$objVariants->attr['pid']

You can also use magic methods to make you object array like.

Comments

1

It sounds like what you really want is sub-classes or a Factory pattern.

For instance you could have a basic product object

class Product {
  protected $_id;
  protected $_sku;
  protected $_name;
  ...
  etc.

  //getters and setters
  etc.
}

... and then use sub-classes to extend that product

final class Book extends Product {
  private $_isbn;
  private $_language;
  private $_numPages;
  ...
  etc.

  public function __construct() {
    parent::__construct();
  }

  //getters and setters
  etc.
}

That way your product types have all the attributes they need and you don't need to try and run around with an "attributes" array - though your CMS needs to be able to support product types (so that if someone wants to add a new book, the fields relevant to books appear in the CMS)... it's just a slightly more OO approach to the problem.

You could then factory pattern it; something like (a really basic example):

class ProductFactory {
  const TYPE_BOOK = 'Book';
  const TYPE_CD = 'CD';
  const TYPE_DVD = 'DVD';
  ...
  etc.

  public static function createProduct($sProductType) {
    if(class_exists($sProductType)) {
      return new $sProductType();
    }
    else {
      //throw an exception
    }
  }

}

You can then generate new products with something like:

$oWarAndPeace = ProductFactory::createProduct('Book')

or better yet:

$oWarAndPeace = ProductFactory::createProduct(ProductFactory::TYPE_BOOK)

3 Comments

Thanks for the answer, i'm working within the framework of an ecommerce system in this case so i'm having to use the class and object structure that's there.
bummer - going to be one of the foreach loops in anyone else's answers then :)
still, you get +1 for the nice answer from me ;)
0

Try something like this:

$arrVariants[] = Array(
  'pid' => $objVariants->pid,
  'price' => $objVariants->price
);

while( $objVariants->next() )
{
  foreach( $arrVariantAttr as $attr )
  {
    end($arrVariants)[$attr['name']] = $objVariants->$attr['name'];
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.