Reputation: 349
First of all forgive me I'm a very beginner to the codeigniter framework. I want to display all the sub contents of parent array in the view. I assume that my data retrieving part is done and now I need to know how to get values by using foreach. I used foreach but I'm getting errors (Illegal string offset). Here is the var_dump values that I am getting to my page.
array(1) {
["post"]=>
array(6) {
["post_id"]=>
string(2) "52"
["status"]=>
string(29) "This is a test status update."
["user"]=>
string(1) "1"
["time"]=>
string(19) "2015-02-05 19:47:42"
["modified"]=>
string(19) "0000-00-00 00:00:00"
["comment"]=>
array(2) {
[0]=>
array(3) {
["comment_id"]=>
string(1) "3"
["comment"]=>
string(22) "This is a test comment"
["comment_datetime"]=>
string(19) "2015-02-06 08:36:15"
}
[1]=>
array(3) {
["comment_id"]=>
string(1) "5"
["comment"]=>
string(11) "sdfsdfsdfds"
["comment_datetime"]=>
string(19) "2015-02-06 09:33:25"
}
}
}
}
I have tried by getting data like this:
<?php
foreach($post as $data){
$data['status'];
$data['post_id'];
}
?>
But, when I do this I'm getting illegal string offset error message.
Upvotes: 0
Views: 1401
Reputation: 104
Try this you will get the result as you want:
foreach($posts as $data)
{
echo $data['post_id'];
echo $data['status'];
echo $data['user'];
echo $data['time'];
echo $data['modified'];
foreach($data['comment'] as $sub)
{
echo $sub['comment_id'];
echo $sub['comment'];
echo $sub['comment_datetime'];
}
}
Upvotes: 0
Reputation: 473
Try this..
<?php
foreach($post->result_array() as $data){
$data['status'];
$data['post_id'];
}
?>
Upvotes: 0
Reputation: 354
before you pass the data to the view put current($dataset) and pass it to view. So you can access it by $post['commnents']
$this->load->view('your_view_name',current($data_set_passing));
Upvotes: 1
Reputation: 930
Since the posts array is associate array , you better use $posts['post'] instead in foreach . here is the link i shared to get it solved http://goo.gl/W7JgAQ
Upvotes: 0
Reputation: 567
try this code
<?php
foreach($post as $data){
$data['post']['status'];
$data['post']['post_id'];
}
?>
Upvotes: 0
Reputation: 12391
if you look clearly at the data
$data['post_id'];
is not in your array, it is there in the data within the $data['post'], there are arrays within array.. so you need to look for the data accordingly.
In order to access keys and values in the code, you can use
foreach($post as $key=>$value){
// $key will have the keys and $value will have the corresponding values
}
Upvotes: 1
Reputation: 2622
You should use
foreach ($post['post'] as $data)
If the array you are printing is called $post, as you can see this is a nested array.
Upvotes: 0