PHP to feed the json_decode() function with an PHP Array? - php

I have a proper .json physical file and i read it from PHP by parsing it.
Let's say the sales.json contains:
{
"custid" : "7761",
"items" : [
{
"itemcode" : "A11231G",
"suppliers" : [
{
"id" : "s10001",
"name" : "Benny & John",
},
{
"id" : "s10004",
"name" : "Colorado Dimension",
}
]
}
]
}
Then i consume it from PHP:
$sales = json_decode( file_get_contents("store/sales.json"), true );
There is no problem and $sales is already become an Array which is ok.
Now for some reason, i want to feed that json_decode() function with an PHP Array (instead of the .json physical file).
I know it is the dumb way that i am actually doing like converting, Array -> json -> Array, which is finally Array to Array.
But for whatever reason i have,
Even if i have a PHP Array() with the correct structure, if i use json_encode($phpArray), then to feed as json_decode( json_encode($phpArray), true ), will it give the exact object like i get from json_decode("sales.json") file?
(or) how can i feed the json_decode function with a PHP Array() object i have?

Actually, json_decode returns a STD object, not an array. To get an array from a JSON string you need to use json_decode($string, true).

Related

How do you detect if a key is used twice in a JSON file with PHP?

I am trying to created an error checking routine for an inbound JSON file in PHP. The file that should produce an error is encoded as;
{
"id" : 4,
"id" : 3,
"id" : 2,
"id" : 1
}
How do I detect that "id" is used more than once instead of just letting the last value of id make it to the JSON object? This is my overly simplistic code;
$data = json_decode(file_get_contents("php://input"));
print_r($data);
it produces the result;
stdClass Object
(
[id
] => 1
)
Other than testing the string with substr_count() for multiple instances of '"id"' is there a better (more efficient?) way to accomplish this task?

How to edit data sql for Json output

I want to add this symbol [ ] to the column "Post_images"
with basis data sql server
Like this,
“post_images” : “ht tp://img*sample*com/gambar1*jpg”, “ht tp://img*sample*com/gambar2*jpg”
to
“post_images” : [“ht tp://img*sample*com/gambar1*jpg”, “ht tp://img*sample*com/gambar2*jpg”]
In json the [] indicates a set of items.
Assuming you have an array with both strings inside then calling json_encode(array) should add the [ ].
See also this tutorial for more detais.
http://www.tutorialspoint.com/json/json_php_example.htm
Please do not write json on your own. Use the php functions instead.
You have to place array for post_images
it mean if you have $data which you json_encodeing you should add your post images as sub array not string. Example
$data = array(
'param1' => "data ...",
'post_images' => array(
“ht tp://img*sample*com/gambar1*jpg”,
“ht tp://img*sample*com/gambar1*jpg”
);
);
echo json_encode($data); // will output what you where looking for
Do the the following:
'["ht tp://imgsamplecom/gambar1*jpg", "ht tp://imgsamplecom/gambar2*jpg"]'
Example:
http://sqlfiddle.com/#!9/971279/1

add value to JSON of title

I search a lot in stack and google try to find the answer which seems to be easy but I'm still stuck with it
I write a code to encode json with values I wanted from . and I would like to add a key / value to the JSON
the JSON is as following structure
{
- files: [
{
title: "works",
- tracks: [
{
title: "File",
format: "mp3"
}
]
},
-{
title: "season1",
tracks: [
{
title: "Button-1",
format: "wav"
},
-{
title: "Beep-9",
format: "wav"
}
]
}
]
}
I want to add to that a key and its value at the beginning to the json as properties under the title files , I mean that can be read by code as
json[files][new_key]
I tried to set that value like this
$json['new_key'] = "new_value";
but this causes adding numbers to the arrays in json , I don't why they numbered
this numbers affect my reading way of the json as JSONModel in my iOS app
so , I hope you can help me
thanks in advance
Assuming that the new value you want to add varies by file, you would need to loop through $json[files] and insert them per key/value pair.
<?php
for($i=0; $i<count($json); $i++)
$json[files][$i]["new_key"] = "value";
?>
I'm still not sure what you have exactly, but it seems you are trying to manipulate the json string.
If done correctly, that is probably the most efficient solution, but what you could also do is:
use json_decode to generate an array from your json string;
locate the correct section / sub-array where you want to add your data;
use array_unshift to prepend your new key - value pair;
use json_encode to generate a json string from your complete array.
The reason you're getting numbers appearing is because you're adding a key to an array (which functions more or less as a list in JS). So before you basically have the object "files" as a list of objects zero-indexed like any other JS array. When you add the key, JS simply adds your key to the end of your present keys (in your case 0 and 1).
It seems like you have a list of multimedia objects where each has a title and a list of tracks. The most straightforward way to solve your issue would be as follows:
$fileItem['title'] = 'works';
$fileItem['tracks'] = array(
array(
'title' => 'File',
'format' => 'mp3'
)
);
$json['files'][] = $fileItem;
$fileItem['title'] = 'season1';
$fileItem['tracks'] = array(
array(
'title' => 'Button-1',
'format' => 'wav'
),
array(
'title' => 'Beep-9',
'format' => 'wav'
)
);
$json['files'][] = $fileItem;
Then you JSON encode it and return it as you normally would. You can put the above in a loop as well. I lack enough context to recommend exactly how.

jQuery-UI Autocomplete Using URL Source Works With Array of Strings But Not Array of Objects

Using jQuery 1.7.2 and jQuery UI 1.8.18. If I use local data for the source attribute, everything works as expected. According to the documentation, a source array can be an array of string values or an array of objects:
Array: An array can be used for local data. There are two supported
formats:
An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ]
Additionally, the source attribute can be a URL that responds with JSON data formatted as shown above:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
If my JSON responder returns a simple array of strings, autocomplete works exactly as it should. If, however, my JSON responder returns an array of objects formatted as above, the request is made to the URL but the dropdown list is never populated. The JavaScript console shows no errors.
The autocomplete invocation looks like this:
var source_url = '/json/codes.php?type=globalcode&cid=25';
$('.gcode').autocomplete({
minLength: 2,
source: source_url
});
The responder is written in PHP. It is just a stub until I get this problem solved:
header('Content-Type: application/json, charset=UTF-8');
...
if( !$_REQUEST['type'] || !$_REQUEST['cid'] ){
echo('[]');
return false;
}
if( $_REQUEST['type'] == 'globalcode' ){
$cid = sprintf("%d", $_REQUEST['cid']);
$stub = "[ { label: 'Label for 1234', value: '1234' }, { label: 'Label for 5678', value: '5678' } ]";
echo( $stub );
return false;
}
Again, it works with both kinds of arrays when the data is local and it works with an array of string values when the data is remote. When the data is a remote array of objects, the list is never populated and JavaScript throws no errors.
You have invalid JSON, this is never logged in the console.
JSON cannot have single quotes, use double quotes, also use JSONLint to check your JSON.
This is the valid version of your JSON:
[
{
"label": "Labelfor1234",
"value": "1234"
},
{
"label": "Labelfor5678",
"value": "5678"
}
]
You could use json_encode() instead
$stub = array(
array(
"label"=>"Labelfor1234",
"value"=>"1234"
),
array(
"label"=>"Labelfor5678",
"value"=>"5678"
)
);
echo json_encode($stub);

how can i loop through a json array requested from an api?

im requesting information from the instagram api in php like this:
<?php $relation = $instagram->get('users/'.$item->id.'/relationship');
..
which return this json data array for me:
object(stdClass)#58(2){
[
"meta"
]=>object(stdClass)#59(1){
[
"code"
]=>int(200)
}[
"data"
]=>object(stdClass)#60(3){
[
"outgoing_status"
]=>string(7)"follows"[
"target_user_is_private"
]=>bool(true)[
"incoming_status"
]=>string(4)"none"
}
}
note: i used var_dump($relation) to bring this out
what I'm trying to do is loop through this array and display the outgoing status and the incoming status i.e
loop(json-array){
echo outgoing_status;
echo incoming_status;
}
thank you very much..
You have an object (instance of stdClass, the generic object), not an array.
$outgoing_status = $response->data->outgoing_status;
$incoming_status = $response->data->incoming_status;
As a side note, use json_decode($json, TRUE) to return the data as an associative array instead of an object.

Categories