0

This is the php code:

$slavesites = array(
    'Category1' => array('Anchor1', 'http://www.test1.com'),
    'Category2' => array('Anchor2', 'http://www.test2.com')
);

foreach($slavesites as $category => $slavesite){
    echo $category;
    foreach($slavesite as $anc => $url){             
        echo $anc.'<br>'; 
        echo $url.'<br>'; 
    }
}

The problem is when I run the code, i get a "0" and "1":

Category10 **--- WHERE DOES THE 0 COME FROM?**
Anchor1
1 **---- WHERE DOES THE 1 COME FROM?**
http://www.test1.com
Category20 --- WHERE DOES THE 0 COME FROM?
Anchor2
1 ---- WHERE DOES THE 1 COME FROM?
http://www.test2.com

Ty!:) Hope you can help...

2 Answers 2

2

second foreach iterates over array without proper indices set. that way default indices (0,1,2,...) are used and hence the number in output.

e.g. actually your definition is like this:

$slavesites = array(
    'Category1' => array(0 => 'Anchor1', 1 => 'http://www.test1.com'),
    'Category2' => array(0 => 'Anchor2', 1 => 'http://www.test2.com')
);

you should use 'list' instead of 'foreach' in the inner loop:

list($anc, $url) = $slavesite;
Sign up to request clarification or add additional context in comments.

3 Comments

It worked, ty so much.... I have one question tho, is instead of "Category1" and "Category2" values I use the same value, my first foreach loop will show online the second array's data and not the first... this is imp for me becouse sometimes I have the same category for multiple sites.
you mean like this? array('Cat' => array(...), 'Cat' => array(...)) ?
yeah, definitely you mean that. bad luck this isn't work out way. structure your data like this, if you want to handle add equal categories names: array( 'Category' => array( array('Name', 'url/'), array('Name2', 'url2/')), 'Category2' => ... );
2

If you want to loop through your array like that, you have to store the elements as key-value pairs:

$slavesites = array(
  'Category1' => array('Anchor1' => 'http://www.test1.com'),
  'Category2' => array('Anchor2' => 'http://www.test2.com')
);

The 0 and the 1 are shown because you don't have keys defined and it therefores uses numerical keys.

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.