user1508711
user1508711

Reputation: 57

php loop through array

I am trying to get certain values from an array but got stuck. Here is how the array looks:

array(2) {
  [0]=>
  array(2) {
    ["attribute_code"]=>
    string(12) "manufacturer"
    ["attribute_value"]=>
    string(3) "205"
  }
  [1]=>
  array(2) {
    ["attribute_code"]=>
    string(10) "silhouette"
    ["attribute_value"]=>
    array(1) {
      [0]=>
      string(3) "169"
    }
  }
}

So from it I would like to have attribute_values, and insert it into a new array, so in this example I need 205 and 169. But the problem is that attribute_value can be array or string. This is what I have right now but it only gets me the first value - 205.

foreach ($array as $k => $v) {
  $vMine[] = $v['attribute_value'];
}

What I am missing here?

Thank you!

Upvotes: 1

Views: 85

Answers (3)

MH2K9
MH2K9

Reputation: 12039

I suggest you to use array_map instead of for loop. You can try something like this..

$vMine = array_map(function($v) {
    return is_array($v['attribute_value']) ? current($v['attribute_value']) : $v['attribute_value'];
}, $arr);

print '<pre>';
print_r($vMine);

Upvotes: 0

Godzilla
Godzilla

Reputation: 318

Try the shorthand version:

foreach ($array as $k => $v) {
  $vMine[] = is_array($v['attribute_value']) ? current($v['attribute_value']):$v['attribute_value'];
}

or the longer easier to understand version, both is the same:

foreach ($array as $k => $v) {
    if(is_array($v['attribute_value'])) { 
        $vMine[] = current($v['attribute_value']);
    } else {
        $vMine[] = $v['attribute_value']; 
    }
}

Upvotes: 0

Kevin
Kevin

Reputation: 41885

If sometimes, attribute_value can be an array, and inside it the values, you can just check inside the loop (Provided this is the max level) using is_array() function. Example:

$vMine = array();
foreach ($array as $k => $v) {
    if(is_array($v['attribute_value'])) { // check if its an array
        // if yes merge their contents
        $vMine = array_merge($vMine, $v['attribute_value']);
    } else {
        $vMine[] = $v['attribute_value']; // if just a string, then just push it
    }
}

Upvotes: 1

Related Questions