Zagloo
Zagloo

Reputation: 1387

How to wrap item from loop into element with concatenation?

I'm trying to push some items from loops to get a string of characters.

I have an $liste_mots array:

  0 => 
    array (size=5)
      'mot' => 
        array (size=7)
          0 => 
            array (size=5)
              'mot' => string 'My'
              'start' => float 0
              'end' => float 1 
          1 => 
            array (size=5)
              'mot' => string 'Name'  
              'start' => float 2
              'end' => float 3         
      'ID' => float 1

1 => 
    array (size=5)
      'mot' => 
        array (size=7)
          0 => 
            array (size=5)
              'mot' => string 'Is'
              'start' => float 4
              'end' => float 5 
          1 => 
            array (size=5)
              'mot' => string 'Zooboo' 
              'start' => float 6
              'end' => float 7        
      'ID' => float 2

What I'm trying to have, is something like that:

<div id='1'><span data-start='0' data-end='1'>My</span><span data-start='2' data-end='3'>Name</span></div><div id='2'><span data-start='4' data-end='5'>Is</span><span data-start='6' data-end='7'>Zooboo</span></div>

I did that:

$response = "";
      foreach ($liste_mots as $key => $item) {
             $response  = "<div id='" . $item['ID'] . "'>";
                foreach ($liste_mots[$key]['mot'] as $idx => $itm) {
                    $response .= "<span data-start='".$itm['start']."' data-end='".$itm['end']."'>" . $itm['mot'] . "</span></div>";
                }
            }
var_dump($response); die;

but with a var_dump, I have just the last div without span into...

Where am I wrong?

Upvotes: 1

Views: 70

Answers (2)

Navneet Garg
Navneet Garg

Reputation: 1374

you are closing div in wrong loop it should like this

$response = "";
foreach ($liste_mots as $key => $item) {
    $response  .= "<div id='" . $item['ID'] . "'>";
        foreach ($liste_mots[$key]['mot'] as $idx => $itm) {
            $response .= "<span data-start='".$itm['start']."' data-end='".$itm['end']."'>" . $item['mot'] . "</span>";
        }
    $response  .= "</div>";
}
var_dump($response); die;

Upvotes: 1

Barmar
Barmar

Reputation: 781751

You're resetting $response each time through the outer loop. You need to use concatenation there, just like you do in the inner loop. You also need to end the div in the outer loop, not after each span in the inner loop.

$response = "";
foreach ($liste_mots as $key => $item) {
    $response .= "<div id='" . $item['ID'] . "'>";
    foreach ($liste_mots[$key]['mot'] as $idx => $itm) {
        $response .= "<span data-start='".$itm['start']."' data-end='".$itm['end']."'>" . $itm['mot'] . "</span>";
    }
    $response .= "</div>";
}
var_dump($response); die;

Upvotes: 1

Related Questions