Welcome Guest, Not a member yet? Register   Sign In
Iterate over a DB function, JSON_ARRAY in CI4
#1

Hi, I'm storing a JSON_ARRAY in the DB(10.4.22-MariaDB) , with 2 tables (`hotel` and a `services`) joined,  following is the `services` Model's save method:

PHP Code:
public function saveServices($data)
 {
    $db db_connect();
    $db->query("INSERT INTO services(
        h_id,
        dining, 
        ) VALUES (
            :h_id:,
            JSON_ARRAY(:dining:))"
$data);
 } 


Which is working good, The Problem I'm having is, when I query the results and send them to Views, I cannot seems to iterate over the VALUES in the JSON_ARRAY, when I use a [foreach] loop in my Views, the result queries the whole array including the square brackets and such, for eg. like this: ["breakfast", "lunch", "dinner"]

Following is my `Home` Controller's read method which I use to send to my Views:

PHP Code:
public function readHotelAndServiceBy($id)
{
        $hotel = new HotelModel();
        $services = new ServicesModel();

        $data = [
            'hotel' => $hotel->SELECT('hotel_name''hotel_desc')->find($id),
            'dining' => $services->SELECT("dining")->find($id),
        ];
        return view('readhotel'$data);



I have used both json_encode and json_decode functions too, but the results end up the same.

What is the best way to itterate over the JSON_ARRAY , which queries it's VALUES as the following (without the square brackets):

breakfast
lunch
dinner


Hope I make myself clear.
Thanks.
Reply
#2

I don't understand what problem you are facing.
You get JSON from the database.
Decode and get an array.
Reply
#3

Hi, I've managed to solve this problem, below is my code. Hope it helps somebody

<?php foreach ($value as $i=>$vals): ?>
<?php foreach(json_decode($vals) as $x=>$y):?>
<?= $y ?>
<?php endforeach ?>
<?php endforeach;

First I iterated over the Json array as my question asked, and on the Second Iteration, I managed to get the VALUES of the First iteration. Anyways if there is a more elegant way to do this, Ill gladly accept any suggestions. Smile
Thanks.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB