Question

I have the following array format. I need to extract the array to get all the attributes

Consider this is my sample result

Array
(
    [0] => Array
        (
            [bean_id] => 7628
            [product_id] => 7389
            [sku] => 950981-1
            [item_value] => Color:Green;Size:M
        )

    [1] => Array
        (
            [bean_id] => 7629
            [product_id] => 7389
            [sku] => 950981-2
            [item_value] => Size:L;Color:Green
        )

    [2] => Array
        (
            [bean_id] => 7630
            [product_id] => 7389
            [sku] => 950981-3
            [item_value] => Size:XL;Color:Green
        )

)

I have used the following loop to extract all the item_value;

foreach($attributes as $attribute) {
    list($key, $value) = explode(':', $attribute['item_value']);
    $product_attribute[$key][$attribute['sku']] .= $value.',';
} 
print_r($product_attribute); exit;

The above statement produces the output as

Array
 (
   [Color] => Array
     (
       [950981-1] => Green;Size, #Here i need to get only Green not **;size,**
     )    
   [Size] => Array
     (
       [950981-2] => L;Color,
       [950981-3] => XL;Color,
     )
 )
Was it helpful?

Solution

Try this:

$product_attribute = array();
foreach ($products as $product) {
    $sku = $product['sku'];
    foreach (explode(';', $product['item_value']) as $attr) {
        list($name, $val) = explode(':', $attr);
        $product_attribute[$name][$sku] = $val;
    }
} 

OTHER TIPS

I assume your array is named $prodattrs

foreach( $prodattrs as $no => $prodattr ) {
    foreach ( $prodattr as $field => $value ) {
       switch ( $field ) {
       case 'item_value':
          $atribs = explode(';', $value);
          foreach ( $atribs as $attr ) {
              list($name, $val) = explode(':', $attr);
            // do what do you want to do
          }
          break;
       case 'sku':
          //.....
          break; 
       case 'bean_id':
          //.....
          break; 
       case 'product_id':
          //.....
          break; 
       }
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top