joun
joun

Reputation: 664

How to turn get the value of json format to array

I am using laravel 5. I query dates from this query:

 $data = DB::table('itemregistrations')
         ->select('itemregistrations.dd', 'itemregistrations.mm', 'itemregistrations.yy')
         ->where('itemregistrations.itemregistrationid', $id)
         ->get();

I want to get the value to put in an array so that i can implode the array into string. I cannot implode it in this format.

dd($data); 

produce this:

Collection {#521 ▼
#items: array:1 [▼
0 => {#515 ▼
  +"dd": 15
  +"mm": "0"
  +"yy": 2007
  }
 ]
}

How to turn this result to:

 0 => {15, 0, 2007}

Thank you

Upvotes: 0

Views: 100

Answers (2)

joun
joun

Reputation: 664

Hope it helps other..

I find solution guided by those comments from this question here:

How do I implode a json object to a string in php?

I modify my code:

  //query tarikh masuk                    
   $datatarikh = DB::table('itemregistrations')
                ->select('itemregistrations.dd', 'itemregistrations.mm', 'itemregistrations.yy')
                ->where('itemregistrations.itemregistrationid', $id)
                ->get();

    //**************** format the value of the date************************                      
    $data = json_decode($datatarikh, true); 

    $val_arr = array();

    foreach($data  as $val)
    {
        foreach($val as $key => $value)
        {
             $val_arr[] = $value;
        }
    }

    $result = implode("-", $val_arr);

It changes associative array to indexed array to be imploded. Thanks for your input.

From an array:

 array:1 [▼
 0 => array:3 [▼
"pdrm_dd" => 15
"pdrm_mm" => "01"
"pdrm_yy" => 2007
 ]
]

The output result:

 "15-01-2007"

Upvotes: 0

Chirag Chaudhari
Chirag Chaudhari

Reputation: 1827

why don't you convert the collection to an array using toArray() method and then simply do the json_encode on the array you got. later on you can even pass it in your response.

Upvotes: 1

Related Questions