Create subset of php array and convert to json - php

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?

Try this
$array = array();
for($i = 0 ; $i<count($your_array);$i++) {
$a=array();
$a['date'] = $your_array[$i]['date'];
$a['price'] = date("F .j",strtotime($your_array[$i]["date"]));
array_push($array,$a);
}
json_encode($array);
Output
[{"date":"Mar. 15","price":"50"},{"date":"Mar. 15","price":"45"},{"date":"Mar. 15","price":"50"}]
Codepad

This should get you there
$ret = array();
foreach ($source as $rec){
$ret[] = array("date"=>$rec["date"], "price"=>$rec["price"]);
}
$json = json_encode($ret);

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

You need to reconstruct array using correct foreach and the use json_encode to get the json
$req_array = array();
foreach($youArray as $value)
{
$temp = array();
$temp['date'] = $value['date'];
$temp['price'] = $value['price'];
$req_array[] = $temp;
}
$json = json_encode($req_array);
echo $json;
see demo
Hope it helps you

$infos =array(
array("id" =>"1","price"=>"50","date"=>"2013-05-15 01:58:48"),
array("id" =>"2","price"=>"55","date"=>"2013-06-15 01:58:48")
);
$i=0;
foreach ($infos as $info )
{
$infos[$i]["date"]= date("F .j",strtotime($info["date"]));
$i++;
}
echo json_encode($infos);

Related

Change the key of first arrays in three dimensional array in PHP

The following code gives the array below, however I need it formatted differently (stated after the array), so it will work for a javascript function I've already written.
$sql = "SELECT towhich, duedate, amount FROM sales WHERE email = '$email' ORDER BY duedate ASC";
$result = mysqli_query($conn, $sql);
$dbarray = array();
while($row = mysqli_fetch_assoc($result)) {
$dbarray[] = $row;
}
$graph = array();
$cnt = 0;
foreach($dbarray as $key => $values){
$orderdate = explode('-', $values['duedate']);
$month = $orderdate[1];
$graph[$month][$cnt] = array (
0 => $values['amount'],
1 => $values['towhich']
);
$cnt ++;
}
//Now it's grouped by date
Array output:
array(5)
{
["02"]=> array(2)
{
[0]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
[1]=> array(2) { [0]=> string(2) "30" [1]=> string(9) "the co op" }
}
["03"]=> array(1)
{
[2]=> array(2) { [0]=> string(2) "50" [1]=> string(9) "the co op" }
}
["04"]=> array(1)
{
[3]=> array(2) {[0]=> string(2) "40" [1]=> string(9) "the co op" }
}
["05"]=> array(2)
{
[4]=> array(2) {[0]=> string(2) "10" [1]=> string(9) "the co op" }
[5]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
}
["06"]=> array(1)
{
[6]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
}
}
The key index value for array should not be, for example, ['02'], but, being the first in the containing array, [0], like normal; and '03' should be [1].
I've looked around a lot, indeed it helped with what bit of code I've produced, however all answers seem to deal with changing the key value further inside the large array. I'm new with multidimensional arrays, btw. Thanks in advance.
In case you're wondering why I've done it like so, so far, it's because each first array should correspond to a different month; that's why I've ordered by date and all that.
If I got you right, you can use: array_values :
$graph = array_values($graph);
so "02" will be 0, "03" will be 1 , ... etc.
$key in your foreach will be the relative record number that the row occurs in the query.
$graph = array();
$cnt = 0;
foreach($dbarray as $key => $values){
$orderdate = explode('-', $values['duedate']);
$month = $orderdate[1];
$graph[$month][$cnt] = array (
$graph[$key] = array (
$month,
$values['amount'],
$values['towhich']
);
$cnt ++;
}

Value in array is a string not an integer

I have a multi-dimensional array which I need to pass to Google Charts. The script is called via Ajax, runs three times and then passes back the array encoded with json_encode. I then needed to add headers to the array so I used array_unshift().
Here is the script
$dataArray = array();
$i = 0;
foreach ($arrSiteValue as $key => $value) {
if($i == 3){
break;
}
$dataArray[$key] = $value;
$i ++;
}
array_unshift($dataArray, array("Terms","Visits"));
echo json_encode($php_array);
Here is what is returned:
Note: Where it says (not set) and (not provided), They are correct values for the string and need to be that.
The value of the key should be an integer however it is getting passed back as a string
How can I get it so that the value is added as an integer?
Here is a dummy array (that works) to show what format the array should be outputted like:
$php_array = array(
array('Terms', 'Visits'),
array('test', 90),
array('joke', 90),
array('funny', 11)
);
And this is what this dummy array ouputs (which is how I need it):
*When I change the line to include (int) as recommenced by some of the users here I get this result:
Edit
These are the lines that get the data from the Google Analytics Library:
if (!$_GET["rangeStartDate"]) {
$startDate = date("Y-m-d", mktime(0, 0, 0, date("m")-1, date("d")-1, date("Y")));
$endDate = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d")-1, date("Y")));
} else {
$startDate = $_GET["rangeStartDate"];
$endDate = $_GET["rangeEndDate"];
}
$metrics = "ga:visits";
$dimensions = "ga:keyword";
$filters = "ga:keyword==(not set)";
$optParams = array('dimensions' => $dimensions, 'filters' => $filters);
$arrSiteResults = $service->data_ga->get($ids,$startDate,$endDate,$metrics,$optParams);
$notSetVisits = $arrSiteResults['rows'][0][1];
// Visits and Page Views
$metrics = "ga:visits";
$dimensions = "ga:keyword";
$optParams = array('dimensions' => $dimensions, 'sort' => '-ga:visits', 'max-results' => '12');
$arrSiteResults = $service->data_ga->get($ids,$startDate,$endDate,$metrics,$optParams);
$arrSiteValue = $arrSiteResults['rows'];
Here is var_dump of: $arrSiteValue:
array(12) { [0]=> array(2) { [0]=> string(9) "(not set)" [1]=> string(4) "2582" } [1]=> array(2) { [0]=> string(14) "(not provided)" [1]=> string(4) "1504" } [2]=> array(2) { [0]=> string(10) "compass fm" [1]=> string(3) "149" } [3]=> array(2) { [0]=> string(18) "compass fm grimsby" [1]=> string(2) "25" } [4]=> array(2) { [0]=> string(9) "compassfm" [1]=> string(2) "10" } [5]=> array(2) { [0]=> string(15) "compassfm.co.uk" [1]=> string(1) "9" } [6]=> array(2) { [0]=> string(16) "compass fm radio" [1]=> string(1) "8" } [7]=> array(2) { [0]=> string(18) "grimsby rugby club" [1]=> string(1) "8" } [8]=> array(2) { [0]=> string(13) "compass radio" [1]=> string(1) "7" } [9]=> array(2) { [0]=> string(21) "compass radio grimsby" [1]=> string(1) "5" } [10]=> array(2) { [0]=> string(19) "www.compassfm.co.uk" [1]=> string(1) "5" } [11]=> array(2) { [0]=> string(15) "compass fm news" [1]=> string(1) "4" }}
PHP's json_encode function will always encode PHP strings as JSON strings. If the data goes into JSON as a string, it was a string in PHP as well.
Why it is a string in PHP is an interesting question. Perhaps the data comes from a database?
In any case, the solution is to convert the string into an integer (with (int)) when you pass it to json_encode:
$dataArray[$key] = (int) $value;
NB that I wouldn't check with is_numeric. The API is clearly expecting the value to be an integer, so I'd suggest you provide one. If the value can't be converted, it will be 0, which is probably a sensible default in your case.
OK, the above code is wrong, because it attempts to convert the array into an integer. The problem, then, is how that array is constructed. It's very hard to help you fix this if you can't show the line of code that creates the value that isn't working.
But I'll bet £5 that the solution is (int).
Per the latest update. I hadn't realised the data was coming from Google Analytics. You get the data and it looks like this: [1]=> string(4) "2582". That is obviously a string that contains number characters. You need to convert this to a number using (int). You should do this in your loop:
if($i == 3){
break;
}
$value[1] = (int) $value[1]; // cast the number to an int
$dataArray[$key] = $value;
Try changing assignment line to this:
$dataArray[$key] = is_numeric($value) ? (int)$value : $value;
Note: it's not a generic solution, but will work in this particular case.
Use intval() (assuming they're all integers, otherwise use floatval()).
$dataArray = array();
$i = 0;
foreach ($arrSiteValue as $key => $value) {
if($i == 3){
break;
}
$dataArray[$key] = intval($value);
$i ++;
}
array_unshift($dataArray, array("Terms","Visits"));
echo json_encode($php_array);
Assuming you can't change the data at its source (you say it is coming from an external API), you may have to explicitly convert the string to an integer yourself:
$dataArray[$key] = intval($value, 10);
or
$dataArray[$key] = (int)$value;
You may want to check that $value is actually a valid number before converting it - use is_numeric for that

Get value in PHP from JSON

I need to get the objects information for "label", "name" where value=true in a PHP variable and not were value=false.
How is this done with this JSON array?
If I make a var_dump of the JSON I get this:
array(8) {
[0]=>
object(stdClass)#8 (3) {
["label"]=>
string(4) "Name"
["name"]=>
string(7) "txtName"
["value"]=>
bool(true)
}
[1]=>
object(stdClass)#9 (3) {
["label"]=>
string(6) "E-mail"
["name"]=>
string(8) "txtEmail"
["value"]=>
bool(true)
}
[2]=>
object(stdClass)#10 (3) {
["label"]=>
string(12) "Phone Number"
["name"]=>
string(8) "txtPhone"
["value"]=>
bool(false)
}
[3]=>
object(stdClass)#11 (3) {
["label"]=>
string(19) "Mobile Phone Number"
["name"]=>
string(14) "txtMobilePhone"
["value"]=>
bool(false)
}
}
$arr = array();
$i = 0;
foreach($json as $key => $items) {
if($items->value == true) {
$arr[$i]['label'] = $items->label;
$arr[$i]['name'] = $items->name;
$i++;
}
}
You can decode it as an object or an array, in this example I use an array.
First you want to take the JSON encoded information and decode it into a PHP array, you can use json_decode() for this:
$data = json_decode($thejson,true);
//the Boolean argument is to have the function return an array rather than an object
Then you can loop through it as you would a normal array, and build a new array containing only elements where 'value' matches your needs:
foreach($data as $item) {
if($item['value'] == true) {
$result[] = $item;
}
}
You then have the array
$result
at your disposal.
Simplification of the suggestions proposed by users JohnnyFaldo and som:
$data = json_decode($thejson, true);
$result = array_filter($data, function($row) {
return $row['value'] == true;
});

PHP & JSON: How can I get a value from where another value equals xyz?

I'm receiving a JSON and trying to interpret some values using PHP.
Example snippet from a JSON dump:
["11811"]=>
object(stdClass)#15 (11) {
["parent_area"]=>
NULL
["generation_high"]=>
int(19)
["all_names"]=>
object(stdClass)#16 (0) {
}
["id"]=>
int(11811)
["codes"]=>
object(stdClass)#17 (3) {
["ons"]=>
string(2) "08"
["gss"]=>
string(9) "E15000008"
["unit_id"]=>
string(5) "41421"
}
["name"]=>
string(10) "South East"
["country"]=>
string(1) "E"
["type_name"]=>
string(15) "European region"
["generation_low"]=>
int(1)
["country_name"]=>
string(7) "England"
["type"]=>
string(3) "EUR"
}
As there is lots of (nested) data, I need to obtain the value of ["name"] where ["type_name"] == 'European region'.
Thanks.
You could use array_filter()
$data_array = array(...);
function is_european($data) {
return $data->type_name == 'European region';
}
$filtered = array_filter($data_array,'is_european');
And then use filtered array to obtain values.
Maybe a better way would be to use JsonPath, like this, assuming your array is a result of decoding JSON (object):
$names = jsonPath($data_object, "$.[?(#['type_name'] == 'European region')].name");
Haven't tried this myself, it may need a bit of correction.
Try this:
<?php
$json = JSON_decode(str,true);
$arr = Array();
foreach($json as $f) {
/* eg. $f = $json["11811"] */
if($f['type_name'] == 'European region') {
$arr[] = $f['name'];
}
}
?>

How to update a multi-array value?

I have this multidimension array in which I need to update a value. What would be the best way to do so? I tried it with 2 foreach loops but wasn't sure if that was the right approach.
Here is the array in question. I need to update the dollar amount on each sub array (i.e. add 3 to it).
array(6) { ["Ground"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "13.63" }
["3 Day Select"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "25.26" }
["2nd Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "32.43" }
["Next Day Air Saver"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "63.00" }
["Next Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "68.65" }
["Next Day Air Early AM"]=> array(2) { [0]=> string(3) "USD" [1]=> string(6) "103.68" } }
Your foreach loop approach would be correct, unless you expect the data format to change e.g. to have more nested levels. If that were the case, then a recursive function would be best suited.
Also, if the data is expected to remain uniform, you could do this:
foreach( $my_array as $index => $row ){
$my_array[$index][1] += 3;
}
cheers!
foreach ($arr as $k=>$row) {
$arr[$k][1] = floatval($row[1]) + 3;
}
foreach ($array as &$subarray) {
foreach ($subarray as $key=>&$value) {
// do whatever you want with $value
// ...
$value = 'something else'; // example
}
}
Try this:
<?php
foreach($first_array as $first_dem_key)
$first_array[$first_dem_key][1] = $first_array[$first_dem_key][1] + 3;
?>

Categories