<?php
require "connect.php";
$query = "SELECT DISTINCT * FROM playlist ORDER BY rand() LIMIT 3";
class PlaylistToday{
public $id; // Tên thuộc tính phải trùng với tên cột 'id' trong cơ sở dữ liệu
public $title; // Tên thuộc tính phải trùng với tên cột 'title' trong cơ sở dữ liệu
public $artUrl; // Tên thuộc tính phải trùng với tên cột 'artUrl' trong cơ sở dữ liệu
function __construct($id, $title, $artUrl) {
$this->id = $id;
$this->title = $title;
$this->artUrl = $artUrl;
}
}
$arrayplaylistfortoday = array();
$data = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($data)) {
array_push($arrayplaylistfortoday, new PlaylistToday($row['id']
,$row['title']
,$row['artUrl']));
}
// var_dump($arrayplaylistfortoday);
// echo json_encode($arrayplaylistfortoday);
?>
var_dump($arrayplaylistfortoday); This code works but that code does not ( echo json_encode($arrayplaylistfortoday)
Self-declared class PlaylistToday does not natively support casting to arrays and hence cannot be json_encoded. If you ultimately need json, you need not use a class to re-encapsulate the data, just use a normal array.
Please format your code when posting a support request, thank you.
I’m with @chiucs123: for json_encode to work, the data must actually be serializable. var_dump will display whatever you put into it, but json_encode is more strict.
That’s one way to do it, yes.
Another way to do this is to have your PlaylistToday implement the JsonSerializable interface. That way, you can tell how an object of that class should be converted to JSON.
I’m sorry, I was wrong. I thought you couldn’t just convert an object to JSON, but it appears that you can:
If a value to be serialized is an object, then by default only publicly visible properties will be included. Alternatively, a class may implement JsonSerializable to control how its values are serialized to JSON.