0

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?

0

2 Answers 2

2
$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);
Sign up to request clarification or add additional context in comments.

Comments

1

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).

3 Comments

Thanks but I don't think user_name or user_id will ever have quotes in it
Yes, I don't think so too. But this is a good coding practice, you will avoid PHP errors with it. It is defensive programming. Unless you are sure that these data is already treated.
so you think in coding is good to do extra things even though are not necessary? I tested it and the system won't let me add ' for usernames

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.