0

I'm having a bit of trouble accessing data within an array that looks like the following:

array ( 
    0 => array ( 'value' => '46', 'label' => 'Brand A', ), 
    1 => array ( 'value' => '45', 'label' => 'Brand B', ), 
    2 => array ( 'value' => '570', 'label' => 'Brand C', ), 
);

Essentially I want to be able to return the contents of the label when given the value (e.g. 45 returns Brand B), but am not sure how to do this within these levels.

Do I need to break this array down into smaller chunks through a loop of some sort to access this data?

Thanks

2
  • Whathaveyoutried.com? I'll give you a hint. Foreach loop, google multidimensional array search, in_array, array_search etc. Commented Feb 22, 2013 at 6:00
  • Your real problem is that you aren't using those labels as keys instead. Commented Feb 22, 2013 at 6:18

3 Answers 3

1

When creating the array you need to use the value as the key:

array(
    '46' => 'Brand A',
    '45' => 'Brand B',
);

OR

$arrayVar['46'] = 'Brand A';

etc.

If you aren't the one creating the array, then you can foreach loop through it and rework it into a different structure.

Sign up to request clarification or add additional context in comments.

2 Comments

I would've gone with using the label as the key instead of the value, but the point is made - the original array doesn't need to be multidimensional.
I agree, however it's being output that way from the API call. I probably should have asked how it was best to restructure the array to remove the unnecessary dimension - thanks though.
0
<?php
$arr = array ( 
    0 => array ( 'value' => '46', 'label' => 'Brand A', ), 
    1 => array ( 'value' => '45', 'label' => 'Brand B', ), 
    2 => array ( 'value' => '570', 'label' => 'Brand C', ), 
);

$val = 45; // search for 45

foreach($arr as $vals){
   if($vals['value'] == $val){
      echo "value=".$vals['value'];
      echo "<br>";
      echo "label=".$vals['label'];
   }
}
?>

Comments

0

Try this

<?php
$arr = array ( 
    0 => array ( 'value' => '46', 'label' => 'Brand A', ), 
    1 => array ( 'value' => '45', 'label' => 'Brand B', ), 
    2 => array ( 'value' => '570', 'label' => 'Brand C', ), 
);

foreach($arr as $ele){
echo "value=".$ele['value']." and label=".$ele['label'];
}
?>

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.