JoshuaNa
JoshuaNa

Reputation: 23

PHP from loop to JSON formatting won't match

I have this array

$data = [ 'admin'=>'1', 'natasha'=>'2', 'demo3'=>'3' ]; 

When I output it echo json_encode($data); I get {"admin":"1","natasha":"2","demo3":"3"} and this how I need it and it works well!

Now I'm trying to loop data from database like this:

    $data = array();
    foreach(TopicModel::theListofUsers($topic_cat,30) as $row) {                
       $data[]= array($row->user_name=>$row->user_id);  
    }
    header('Content-Type: application/json');
    echo json_encode($data);

But I'm getting this format [{"demo4":"4"},{"demo3":"3"}] but I need {"admin":"1","natasha":"2","demo3":"3"}

I tried many things, pass strings and convert to array or manipulate array but none of it gave me the proper format. Any idea?

Upvotes: 0

Views: 43

Answers (2)

Fabiano
Fabiano

Reputation: 5199

To achieve what you want, you need to set the name as the array key inside your foreach loop:

$data = array();
foreach(TopicModel::theListofUsers($topic_cat,30) as $row)
{                
   $data[$row->user_name]= $row->user_id;  
}

header('Content-Type: application/json');
echo json_encode($data);

And I suggest that you escape both key and value of your array to avoid unwanted characters, otherwise your json_encode will fail returning false.

A simply way to do it can be: str_replace("'", "", $row->user_name) and str_replace("'", "", $row->user_id).

Upvotes: 1

mlask
mlask

Reputation: 337

$data = array();
foreach(TopicModel::theListofUsers($topic_cat,30) as $row) {                
   $data[$row->user_name] = $row->user_id;
}
header('Content-Type: application/json');
echo json_encode($data);

Upvotes: 2

Related Questions