muasX
muasX

Reputation: 15

Get data from db and display specific array index in view using codeigniter

I want to view a data in view with different style from each data. Thats why I need an array index when load the data from database.
I'm using CodeIgniter, but I still got error like undefined offset.

I tried to select data in my model and order by datetime (timestamp) limit 5 data

Model :

return $this->db->query("select * from artikel order by datetime ASC LIMIT 5");

Controller :

$data['artikels']=$this->Home_model->getartikel();

View :

<?php foreach ($artikels->result_array() as $artikel) { ?>
<div class="style-one"><?php echo $artikel[0]['title'] ?></div>
<div class="style-two"><?php echo $artikel[1]['title'] ?></div>
<div class="style-three"><?php echo $artikel[2]['title'] ?></div>
<div class="style-four"><?php echo $artikel[3]['title'] ?></div>
<div class="style-five"><?php echo $artikel[4]['title'] ?></div>
<?php } ?>

I want the data display like the picture below:

enter image description here

Upvotes: 0

Views: 445

Answers (1)

Sherif Salah
Sherif Salah

Reputation: 2153

You have two options..

First is to change your style with style-# to just match the array indices and use it like this:

<?php foreach ($artikels->result_array() as $key => $artikel) { ?>
    <div class="style-<?= $key ?>"><?= $artike['title'] ?></div>
<?php } ?>

Or to prepare your array in your controller and re-index it using your css styles as its keys.

// That's an array with numbers in words
$numbers = array("zero","one","two","three","four","five");

// That's exactly how result_array() returns your result
$articles = array(
    array('title' => 'Lorem ipsum dolor sit amet.'),
    array('title' => 'Consectetur adipisicing elit. Labore, officia?'),
    array('title' => 'Obcaecati cupiditate, eveniet ducimus est ea sed.'),
    array('title' => 'Iste assumenda, recusandae quasi.'),
    array('title' => 'Voluptas sapiente eos atque, debitis.'),
    array('title' => 'Quod, vel, ipsam.')
);

// That's an empty result array
$result = array();

// Processing in your controller
foreach ($articles as $key => $article)
{
    $result[$numbers[$key]] = $article['title'];
}

The result would be like this:

Array
(
    [zero] => Lorem ipsum dolor sit amet.
    [one] => Consectetur adipisicing elit. Labore, officia?
    [two] => Obcaecati cupiditate, eveniet ducimus est ea sed.
    [three] => Iste assumenda, recusandae quasi.
    [four] => Voluptas sapiente eos atque, debitis.
    [five] => Quod, vel, ipsam.
)

Now in your view you can do this:

<?php foreach ($articles as $key => $title) { ?>
    <div class="style-<?= $key ?>"><?= $title ?></div>
<?php } ?>

Upvotes: 1

Related Questions