get the sub index in foreach loop in simpleXMLElement

后端 未结 5 1047
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 13:38


  
    This is title1
    This is desc1

        
相关标签:
5条回答
  • 2020-12-19 14:25

    You could use SimpleXMLElement::xpath to return an array of the <item> elements, then access the array's keys as you want.

    foreach ($xml->xpath('/items/item') as $key => $item) 
    
    0 讨论(0)
  • 2020-12-19 14:27

    This is because simpleXML structures are not normal arrays but iterators who do not have an array index.

    I don't know of any other solution than keeping track manually using a variable:

     $index = 0;
     $xml = simplexml_load_file('post.xml');
    
     foreach($xml->item as $item )
       {
           ....
           $index++;
        }
    
    0 讨论(0)
  • 2020-12-19 14:29

    Heredoc

    might try

    <a href="#slide-{$key}">
    
    0 讨论(0)
  • 2020-12-19 14:30

    You can use a for loop instead of a foreach like this :

    $item = $xml->item;
    $howMany = count($item);
    for($i = 0; $i < $howMany; $i++){
    echo <<<HTML
                        <li>
                        <div class="published">
                            <span class="day">13</span>
                            Sep 2010
                        </div>
    
                        <div class="summary">
                        <a href="#slide-$i">
                                <h3>$item->title</h3>
                        </a>
                        </div>
                        </li>
    
    HTML;
    }
    
    0 讨论(0)
  • 2020-12-19 14:38

    AFAIK with heredocs format, you need to wrap variables in curly braces:

    <a href="#slide-{$key}">
      <h3>{$item->title}</h3>
    </a>
    
    0 讨论(0)
提交回复
热议问题