Diego_sf93
Diego_sf93

Reputation: 193

Make a list with php order by user and date

I want to make this, a list with all the items of a user, divide by users..

<div id="news-block">
    <h3 id="news-title">USER NAME</h3>
    <ul id="news-content">
        <li>ITEM 1</li>
        <li>ITEM 2</li>
        <li>ITEM 3</li>

    </ul>

I have this php, my problem is with the title:

<div id="news-block">
    <?php
    echo "<ul id='news-content'>";
    $username=null;
    foreach ($programas as $programa) {

        if ($programa->username!= $username) {
            $nombre = $programa->username;
            echo "<h3 id='news-title'>".$programa->username."</h3>";
        }
        echo "<li>".$programa->titulo."</li>";
    }
    echo "</ul>";
    ?>

Obviously this code is wrong, because i can't repeat the name of the user..

Upvotes: 0

Views: 79

Answers (2)

Fez Vrasta
Fez Vrasta

Reputation: 14835

Try this code:

<?php

  $list = "<ul id=\"news-content\">";
  $h3 = "<h3 id=\"news-title\">";
  $username=null;


    foreach ($programas as $programa) {

      if ($username == null) {
        $username = $programa->username;
        $h3 .= $username . "</h3>";
      }
      $list .= "<li>" . $programa->titulo . "</li>";


    }

    $list .= "</ul";

    echo $h3 . $list;


?>

Or do you want a list like:

- Name
-- 1
-- 2
-- 4

- Name
-- 1
-- 2
-- 3

this? If so, we need the structure of your array $programas.

I think $programas is something like:

$programas = array(
        "UserOne" => array("prog1", "prog2", "prog3"),
        "UserTwo" => array("prog1", "prog2", "prog3")
        );

So the code should be:

$users = array_keys($programas);
$i = 0;

foreach($programas as &$user) {


  $h3 = "<h3 id=\"news-title\">" . $users[$i]  . "</h3>";     
  $list = "<ul id=\"news-content\">";

  foreach($user as &$programa) {
    $list .= "<li>$programa</li>";
  }

  echo $h3 . $list . "</ul>";

  $i = $i + 1;
}

Now tested, it works

Upvotes: 2

user979268
user979268

Reputation:

Try this, I didn't test this code, but it should works!

<?php
     $users = array(
    'user1' => array(
        'name' => 'Tom',
        'items' => array( 'item1', 'item2', 'item3' )
        ),
    'user2' => array(
        'name' => 'John',
        'items' => array( 'item1', 'item2', 'item3' )
        )
    );

    foreach($users as $user)
    {
        echo '<h3 id="news-title">'.$user['name'].'</h3>';
        echo '<ul>';
        foreach($user['items'] as $item )
        {
            echo '<li>'.$item.'</li>';
        }
        echo '</ul>';
    }
?>

Upvotes: 0

Related Questions