May 16, 2013

Create subset of php array and convert to json

Dilettante’s Question:

This is one of those that should be easy. I’m not even sure if “subset” is the right way to describe it.

My initial array looks like this:

array(3) { [0]=> array(5) { ["id"]=> string(1) "1" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 01:58:48" ["created"]=> string(19) "2013-05-15 01:58:48" } [1]=> array(5) { ["id"]=> string(2) "11" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "45" ["date"]=> string(19) "2013-05-15 03:34:59" ["created"]=> string(19) "2013-05-15 03:37:01" } [2]=> array(5) { ["id"]=> string(2) "25" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 22:47:46" ["created"]=> string(19) "2013-05-15 22:52:02" } } 

I’d ultimately like to end up with just the date and price values, swap them so that date is first in the array, reformat the date, and convert it to a json array that looks something like this:

[{"date":"Mar. 15","price":"50"},{"date":"Mar. 15","price":"45"},{"date":"Mar. 15","price":"50"}] 

I ran a foreach statement to get at the data and reformat the date, then went out of my league with splice, unset, and other functions that took me in the wrong direction. Any ideas?

Create a quick function to create another array with only selected elements:

function datePriceToJson($array) {
   $a = array();
   foreach($array as $i => $a) {
      $a[] = array("date" => $a['date'], "price" => $a['price']); //Creae a new array based on the one you want
   }
   return json_encode($a);
}

datePriceToJson($array);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!