Converting to json correct way using php? - php

I need an o/p like this ["12","13"] when I do the following json operation
I have a 2 varaiables and getting these values as post data
$a = $_POST['cas'];
$b = $_POST['casty'];
$final1 = json_encode($a);
$final2= json_encode($b);
$final_value = '['.$final1.','.$final2.']';
I am getting output as ["12","13"].I am doing correct way in php ? any other ways to get json object apart from this ?

Use an array for that like this:
$array = array($_POST['cas'], $_POST['casty']);
$final_value = json_encode($array);
Note: no need to create $a and $b.
By adding JSON_FORCE_OBJECT as a 2nd parmeter you'll get key => value data like a normal php array. JSON Arrays don't have keys, therefore most of the time JSON_FORCE_OBJECT is useful.
JSON Array ["data", "data2", "data3"]
JSON Object {0:"data", 1:"data2", 2:"data3"}

Related

Why does my JSON array turn into an object?

I am trying to unset a value from test_bots.json and save it back, but somehow the data format is being changed in the process.
test_bots.json contains this JSON array:
["John","Vladimir","Toni","Joshua","Jessica"]
My code looks like this:
$good = 'Toni';
$good_arr = file_get_contents('test_bots.json');
$good_arr = json_decode($good_arr);
if(in_array($good, $good_arr)){
$key = array_search($good, $good_arr);
unset($good_arr[$key]);
$good_arr2 = json_encode($good_arr);
file_put_contents('test_bots.json',$good_arr2);
}
The output that's saved is:
{"0":"John","1":"Vladimir","3":"Joshua","4":"Jessica"}
but I want the output to look like:
["John","Vladimir","Joshua","Jessica"]
I tried to unserialize the array before saving it, but it's not working.
Why is this happening?
In order for json_encode to convert a PHP array with numeric keys to a JSON array rather than a JSON object, the keys must be sequential. (See example #4 in the PHP manual for json_encode.)
You can accomplish this in your code by using array_values, which will reindex the array after you have removed one of the items.
$good_arr2 = json_encode(array_values($good_arr));

PHP json_Encode an array of json_encode-ed arrays

Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.
Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()
Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode

Convert array of objects with keys to keyed array

I have an array of objects that are defined as {'preference name',value}. For example
$preferences[] = {'abc',123};
$preferences[] = {'def',456};
I'd like to access them like this:
$pref = $preferences['abc'];
Of course, I know I could assign them as a keyed array to begin with, however I'm getting the values via JSON, and json_decode always creates an array of objects. Some example JSON that leads us to the situation above would be:
{'abc':123,'def':456}
Obviously it's trivial to covert these using a loop, but I wondered if there was a better one-liner that might do the job?
If you decode the JSON into associative arrays AND all properties are unique, then just merge the sub arrays:
$preferences = json_decode($json, true);
$preferences = call_user_func_array('array_merge', $preferences);
Seems ugly, but hey, it works.
<?php
$a = ['abc'=>123,'def'=>456];
$obj = json_decode(json_encode($a));
var_dump($obj->abc); //123
$arr = (array)$obj;
var_dump($arr["abc"]); //123

How to get json element's property from Entire Json in PHP

My json value looks like this:
[{"Id":"1169"},{"Id":"1164"},{"Id":"1163"},{"Id":"1162"},{"Id":"1161"}]
Now i want to store only numeric values 1169,1164,1163,1162,1161 into different array.How can i do this?
Simple
$values = array_values(json_decode($json,true));
its not array its a json.
You can change from array to json and json to array.
$a = json_encode($yourArray);
AND
$b= json_decode($yourJson);

I would like json_encode in PHP to return a JSON array even if the indices are not in order

but according to this: http://www.php.net/manual/en/function.json-encode.php#94157 it won't.
I'm using flot so I need to have an array with numeric indexes returned but what I'm getting is this:
jsonp1282668482872 ( {"label":"Hits 2010-08-20","data":{"1281830400":34910,"1281916800":45385,"1282003200":56928,"1282089600":53884,"1282176000":50262,"1281657600":45446,"1281744000":34998}} );
so flot is choking. If I var_dump the array right before I call json_encode it looks like this:
array(7) {
[1281830400]=>
int(34910)
[1281916800]=>
int(45385)
[1282003200]=>
int(56928)
[1282089600]=>
int(53884)
[1282176000]=>
int(50262)
[1281657600]=>
int(45446)
[1281744000]=>
int(34998)
}
any ideas?
As zneak says, Javascript (and thus JSON) arrays cannot have out-of-order array keys. Thus, you either need to accept that you'll be working with JSON objects, not arrays, or call array_values before json_encode:
json_encode(array_values($data));
However, it looks like you're looking to display time series data with flot. As you can see on the flot time series example, it should be a two element array like so:
$.plot(
$('#placeholder'),
[[
[1281830400, 34910],
[1281916800, 45385],
[1282003200, 56928],
[1282089600, 53884],
[1282176000, 50262],
[1281657600, 45446],
[1281744000, 34998]
]],
{
label: 'Hits 2010-08-20',
xaxis: {mode: 'time'}
}
)
Given your array (let's call it $data) we can get the proper JSON like so:
json_encode(
array_map(
function($key, $value) { return array($key, $value); },
array_keys($data),
array_values($data)
)
);
It's conceptually impossible. You cannot encode an array with fixed indices in JSON.
As a reminder, a JSON array looks like this:
[1, 2, 3, 4, 5]
There's no room to put indices there.
You should work on the Javascript side. Accepting that json_encode will return an object, you can convert this object into an array. That shouldn't be too hard.
function toArray(object)
{
var result = [];
for (var key in object)
{
if (!key.match(/^[0-9]+$/)) throw new Error("Key must be all numeric");
result[parseInt(key)] = object[key];
}
return result;
}
You can force json_decode() to produce arrays by passing TRUE as the second parameter, but you can't force json_encode() to produce arrays in the first place:
json_decode($json, TRUE); // force array creation
You can use array_merge to reindex a numerically indexed array, like this:
$a = array(2 => 3, 4 => 5);
$a = array_merge($a);
var_dump($a);
For flot, what you're asking for isn't actually what you want. You want an array of arrays, not an array of numbers. That is, you want something that looks like this:
[[1281830400, 34910],
[1281916800, 45385],
[1282003200, 56928],
[1282089600, 53884],
[1282176000, 50262],
[1281657600, 45446],
[1281744000, 34998]]
As for how to do that in PHP, I'm not sure.

Categories