1

I have an array of 3 columns in which I have the second column which is an array in php.The second column which is an array can have 2-6 rows.

I put the data in the array with key with the below code

$data_array = array(
                  'name' =>$name, 
                  'category_name'=>$category_name,
                  'url'=>$url

);

The second column $category_name in the above $data_array is an array which has data like below

$category_name = array("India", "USA", "UK");

I want to echo the the data in the following format and eventually add it the mysql database

'Jim'
'India'
'www.google.com'

'Jim'
'USA'
'www.google.com'

'Jim'
'UK'
'www.google.com'

'John'
'India'
'www.yahoo.com'

'John'
'USA'
'www.yahoo.com'

'John'
'UK'
'www.yahoo.com'   

If you notice the first and third row remain same and the second row changes according to the data in the category_name array

I am trying to use the below code to achieve this but I am getting no output

for($i=0;$i<count($NPR);$i++){

for($j=0;$j<count($NPR[$i]['category_name'][j]);$j++){

echo "'".$NPR[$i]['name']."'<br>";
echo "'".$NPR[$i]['category_name'][j]."'<br>";
echo "'".$NPR[$i]['url']."'<br>";
}
}

1 Answer 1

3

It should be count($NPR[$i]['category_name']), you added an unnecessary [j] at the end of this.

But it all would be easier if you used foreach

foreach ($NPR as $item) {
    foreach ($item['category_name'] AS $cat) {
        echo "'{$item['name']}'<br>";
        echo "'$cat'<br>";
        echo "'{$item['url']}'<br>";
    }
}

Make sure you have error reporting enabled when you're debugging code. [j] should have produced a warning.

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

1 Comment

Thanks for your help Barmar. I was trying to count the number of columns in the array $category_name by adding [j] in count($NPR[$i]['category_name'][j])

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.