Using a loop to get certain elements from Json

I have a class which contains a method. The method queries everything from a database table and returns the result in json format.

I am then calling that method like so:

Read More
$consultants = new Consultants();
$consultants->getUsersJson();

This returns something like:

[{“con_id”:”1″,”con_firstname”:”Paul”,”con_lastname”:”Bloggs”,”con_username”:”paul@email.com”,”con_password”:”password”,”con_job_category_id”:”0″,”con_updated_at”:”2015-07-08 00:00:00″,”con_created_at”:”2015-07-08 00:00:00″},{“con_id”:”2″,”con_firstname”:”Allan”,”con_lastname”:”Bloggs”,”con_username”:”paul@email.com”,”con_password”:”password”,”con_job_category_id”:”0″,”con_updated_at”:”2015-07-08 00:00:00″,”con_created_at”:”2015-07-08 00:00:00″},{“con_id”:”3″,”con_firstname”:”Ryan “,”con_lastname”:”Bloggs”,”con_username”:”ryan@email.com”,”con_password”:”password”,”con_job_category_id”:”0″,”con_updated_at”:”2015-07-08 00:00:00″,”con_created_at”:”2015-07-08 00:00:00″}]

I now need some sort of loop to go through this as I only require con_firstname, con_lastname and con_username. It also needs to look something similar to this:

{"data"[{"con_firstname":"Ryan","con_lastname":"Bloggs","con_username":"ryan@email.com"}]}

(So that it is all wrapped in “data”. Also this is just one, the loop should show all of them.)

Related posts

2 comments

  1. Try it, it may fail hardcore:

    $consultants = new Consultants();
    $users = $consultants->getUsersJson();
    
    json_decode($users); 
    $users = object_to_array($users); 
    $data = array(
                'data'=>array()
               );
    
    foreach ($users as $user){
        $data['data']['con_firstname'] = $user['con_firstname']
    }
    
    function object_to_array($data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }
        if (is_array($data)) {
            return array_map(__FUNCTION__, $data);
        }
        else {
            return $data;
        }
     }
    
    json_encode($data); 
    
  2. Well, just to compensate on Kisaragi’s answer, you can use ‘json_decode($users,true)’ to get an array directly

Comments are closed.