Skip to content
Advertisement

php pdo json encode array print

When I pull data from the hello database, it just writes the first line, not the other lines, what could be the reason? I did not know much about php json but did not get any results.

İD 88 NOT FOUND

**database print **

[{"title":"facebook","contact":"facebook adres"},
{"title":"twitter","contact":"twitter adres"}]

database data

id:87 [{"title":"facebook","contact":"facebook adres"},
    {"title":"twitter","contact":"twitter adres"}]

id:88
    [{"title":"instagram","contact":"instagram adres"},
    {"title":"google","contact":"google adres"}]

database function

function menu($menu_title)
{
    global $db;
    $query = $db->prepare('SELECT * FROM menu WHERE menu_title = :menu_title');
    $query->execute([
        'menu_title' => $menu_title
    ]);
    $result = $query->fetchAll(PDO::FETCH_ASSOC);

    if ($result) {
        $data = [];
        foreach ($result as $key => $value) {
            $data += json_decode($value['menu_content'], true);
        }
        return $data;
    }
    return null;
}

socialmedia foreach

 <?php foreach (menu('sosyalmedya') as $key => $menu): ?>
 
<?= $menu['title'] ?><br>
<?= $menu['contact'] ?><br>
<?php endforeach; ?>

database data

database print

Advertisement

Answer

You’re only returning the first element of each JSON array. Append the whole array to the result.

        foreach ($result as $value) {
            $data = array_merge($data, json_decode($value['menu_content'], true));
        }

BTW, don’t use SELECT * if you only want the menu_content column. Use SELECT menu_content.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement