Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
1  
So in the original array the items have different structure? –  zerkms 1 hour ago
1  
You can use is_array() to determine if it's an array and if so and you know the first element in that array is the desired value then use reset() to get that value –  xd6_ 1 hour ago

3 Answers 3

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
    }
}
share|improve this answer

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']; 
    }
}
share|improve this answer

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.