0

I am putting the data in multiple array in php and trying to access it through key value pair logic but not getting success

Here's the output when I'm printing the array with print_r:

Array ( 
    [0] => Array ( 
        [33] => Coca Cola Products 
    ) 
    [1] => Array ( 
        [1] => Agricultural products, Food and Beverages 
    ) 
)

The code I'musing:

foreach ($data as $key=>$option)
{
    echo $key;
}

output required:

33 coca cola products
1 Agricultural products, Food and Beverages

In my for-loop for populating data I'm doing this:

$data[] = array($loop['category_id'] => $loop['category_name']);

Now wanted to get category id and category name

3
  • what are you trying to geT? Commented Jun 16, 2017 at 5:59
  • @Exprator updated the question kindly check Commented Jun 16, 2017 at 6:03
  • I'm guessing that category_id's are unique? Why not build you're array like this instead: $data[$loop['category_id']) = $loop['category_name']; and just do this in your foreach: echo $key . ' ' . $option; Commented Jun 16, 2017 at 6:08

3 Answers 3

2

When you populating the array...

data[] = array($loop['category_id'] => $loop['category_name']);

Your creating each element as an array, which is why you end up with the end result you have.

If you used

$data[$loop['category_id']] = $loop['category_name'];

You would see that the array is created at 1 level of depth. Use print_r on this and you will see the difference. This will mean when you iterate over with the foreach it will use the keys you used to add the data and give the values your after.

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

3 Comments

If you're gonna copy/paste my comment, make sure you fix the error in it. :-) It should be $data[$loop['category_id']] and not $data[$loop['category_id']) (the last parenthesis).
The problem I have with comments is that they don't always explain what the problem is, and sorry about copy - it's caffeine hasn't kicked in yet and typing is hard work :-/
Didn't mean to imply that you did anything wrong. Just thought it was a bit funny. :-)
1

Your $data is an array of array, you should do it like this, live demo.

foreach ($data as $v)
{
    echo key($v) . ' ' . current($v) . "\n";
}

Comments

0

This can be done as below

$data = array(array('33'=>"Coca Cola Products"),array("1"=>"Agricultural products, Food and Beverages"));

foreach ($data as $key=>$option)
{
        foreach($option as $k=>$v){
                echo "\n". $k ." ". $v;
        }
}

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.