简体   繁体   中英

Php subarrays code adds extra values

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...

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM