Reputation: 21
I am working with rest api in PHP and I'm getting an array output result. But I want to get data nested within cat_id
. This is my actual output result below:
Array
(
[0] => Array
(
[id] => 16
[user_id] => 1
[cat_id] => 11
[image] => abc.jpg
)
[1] => Array
(
[id] => 16
[user_id] => 2
[cat_id] => 11
[image] => xyz.jpg
)
[2] => Array
(
[id] => 16
[user_id] => 2
[cat_id] => 12
[image] => cde.jpg
)
I want to show the output result via cat_id
like the following array
[0] => Array
(
[cat_id] => 11
{
[image] => abc.jpg
[user_id] => 1
[image] => xyz.jpg
[user_id] => 2
}
[cat_id] => 12
{
[image] => cde.jpg
[user_id] => 2
}
)
Here is my code in controller
$users['rec'] = $this->Model_users->get_categories();
$responseJSON = array("Status" => true,"Message" => "Records","Result" => $users['rec']);
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
Here is my model
$this->load->database();
$this->db->select('*');
$this->db->from('mytable');
$query = $this->db->get();
if ( $query->num_rows() > 0 ){
$rows = $query->result_array();
return $rows;
}else{
return false;
}
Upvotes: 1
Views: 228
Reputation: 1069
You can do this
$cats = array();
foreach ($rows as $value) {
$cats[$value["cat_id"]][] = $value;
}
Now $cats
should be the way you want it.
Upvotes: 1