CI3 (Twig) Query result array is empty
You don't need ->select("*")
. From CodeIgniter docs:
$this->db->select()
...
If you are selecting all (*) from a table you do not need to use this function. When omitted, CodeIgniter assumes that you wish to select all fields and automatically adds ‘SELECT *’.
So you can do just this:
$query = $this->db->get("phrases")->result_array();
By the way, I think that e.g. $phrases
would be a better variable name.
Another doc page describes the result_array()
method:
This method returns the query result as a pure array, or an empty array when no result is produced. Typically you’ll use this in a foreach loop.
So, $query
is an array, so you need to loop through it in Twig. The array is not empty, you even posted its contents to your question. I expanded the contents to multiple rows for readability:
[ 0 => [ 'id' => '31', 'keyword' => 'hello_world', 'value' => 'Hello World', 'language' => 'english' ], 1 => [ 'id' => '35', 'keyword' => 'beautiful_weather', 'value' => 'It\'s a beautiful weather today', 'language' => 'english' ], 2 => [ 'id' => '36', 'keyword' => 'goodbye', 'value' => 'Goodbye!', 'language' => 'english' ], 3 => [ 'id' => '37', 'keyword' => 'test', 'value' => 'Test123', 'language' => 'english' ]]
So, you have four items and each of them has keys id
, keyword
, value
and language
. You can loop through the array in Twig e.g. like this:
{% for item in query %} ID is {{ item.id }} Keyword is {{ item.keyword }} Value is {{ item.value }} Language is {{ item.language }}{% endfor %}
Output:
ID is 31Keyword is hello_worldValue is Hello WorldLanguage is englishID is 35Keyword is beautiful_weatherValue is It's a beautiful weather todayLanguage is englishID is 36Keyword is goodbyeValue is Goodbye!Language is englishID is 37Keyword is testValue is Test123Language is english
Edit:
You can perform the foreach
loop in PHP like this:
$phrase = [];foreach ($query as $result) { $phrase[$result->keyword] = $result->value;}$this->twig->addGlobal("phrase", $phrase);
And then in Twig:
{{ phrase.hello_world }}{{ phrase.beautiful_weather }}{{ phrase.goodbye }}{{ phrase.test }}