1

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!

2
  • 1
    So in the original array the items have different structure? Commented Sep 11, 2014 at 3:09
  • 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 Commented Sep 11, 2014 at 3:11

3 Answers 3

1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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']; 
    }
}

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.