I using an MVC framework with controllers and routes on PHP 5.6.
I am trying to define some PHP variables from the database.
+---------+---------+-------------+---------------+
| meta_id | post_id | meta_key | meta_value |
+---------+---------+-------------+---------------+
| 3506 | 147 | event_flag | 1 |
| 3507 | 147 | event_year | 2019 |
| 3508 | 147 | event_title | Soccer Encore |
+---------+---------+-------------+---------------+
Here I call the query.
// Controller:
public function __construct()
{
parent::__construct();
$this->_data['checklist_content'] = $this->_models['wp_stream_settings']->getChecklistMeta(147);
}
Here is the query:
// Model:
function getChecklistMeta($item_id){ // passed $item_id = 147
$sql = '
SELECT *
FROM '.PREFIX.'wp_postmeta
where post_id = '.$item_id.' and meta_key IN ( "event_flag", "event_year", "event_title" );
';
return $this->db->select($sql, array(':ID' => $item_id));
}
This query will give all the information needed and put the variables in an stdClass object:
// Data
[checklist_content] => Array
(
[0] => stdClass Object
(
[meta_id] => 3506
[post_id] => 147
[meta_key] => event_flag
[meta_value] => 1
)
[1] => stdClass Object
(
[meta_id] => 3507
[post_id] => 147
[meta_key] => event_year
[meta_value] => 2019
)
[2] => stdClass Object
(
[meta_id] => 3508
[post_id] => 147
[meta_key] => event_title
[meta_value] => Soccer Encore
)
)
But I can not manage the array as I want:
echo $data['checklist_content']->{'event_title'};
I tried to use array_search:
print_r(array_search("event_title",$this->_data['checklist_content']));
with no avail.
I could modify the SQL query in order to have more manageble stdClass object, or maybe remapping it in a JSON format, or else.
How can I modify the query or else, in order to get something like this:
// Data
[checklist_content] => Array
(
[event_flag] => 1
[event_year] => 2019
[event_title] => Soccer Encore
)
So that I could easily display the value "Soccer Encore" like this:
echo $data['checklist_content']->{'event_title'};
for now I am forced to get the variables like this:
echo $data['checklist_content'][2]->{'meta_value'}; // Outputs "Soccer Encore"
I am open to redesign the query or even to use a JSON method or a serialisation to be able to mange better the variables.