PhP returning Json in [] - php

Hey I am trying to pass data back in json format using json_encode.
However it seems to return like this:
[{‘county’:’us’,’sector’:’retail’}]
However the end user has said that they expect the response without the square brackets.
How do I do this?
Thanks.

Depends on how you are generating the value you encode... json_encode has an option JSON_FORCE_OBJECT you could use but from what I can see that's probably not what you want, as it seems to me this would only turn the "square brackets" into a wrapper object. Nevertheless, if you'd like to try:
json_encode($value, JSON_FORCE_OBJECT);
Edit: as others have said, it seems likely json_encode($value[0]) is what you want.

Assuming your array is:
$data = [
'country' => 'us',
'sector' => 'retail',
];
Then just return a json_encoded array like so:
json_encode($data);
// {"country":"us","sector":"retail"}
However, if your array with data is "nested" like so:
$data = [[
'country' => 'us',
'sector' => 'retail',
]];
then return the encoded first element of it:
json_encode($data[0]);
// {"country":"us","sector":"retail"}

My experience of this happening is that you're accidentally storing your data as the first item of an array.
For example you may have done:
$json_store = Array();
$json_store[] = Array('country' => 'us', 'sector' => 'retail');
$json = json_encode($json_store);
A way of testing for this is to see if doing the following removes the brackets:
$json_encode($json_store[0])
If it does, you've a unnecessarily nested array that you should fix. Using the above line probably should be avoided as it's better to fix how the data is stored in the first place.

Related

Is there a cleaner way to send an array from a controller to a function, model or view?

Is there a more compact way to send an array to a function?
Here's what I'm currently doing:
$data = array(
'id' => '1'
);
$result = $this->Tests_model->DoSomething($data);
What I'd like to do is just:
$result = $this->Tests_model->DoSomething(array('id' => '1'));
or
$result = $this->Tests_model->DoSomething(('id' => '1'));
...but I can't seem to format the data inside the ( and ). I still want to pass an array, for better code-reuse. Is there a way to do this?
This line
$result = $this->Tests_model->DoSomething(array('id' => '1'));
is completely valid and can be used.
You need to change the third example to make it work. What you're looking for is
$result = $this->Tests_model->DoSomething(['id' => '1']);
The syntax ['id' => '1'] is just another way of writing array('id' => '1') they produce the exact some thing.
One last way to create an array and add a key/value pair to it is like this.
$data['id'] = '1'; //assigns a value of '1' to the key 'id' in an array named $data.
The above is just alternate syntax for writing.
$data = array('id' => '1');
None of these variations on syntax is better or worse other than in terms of "readability" which is often a matter of opinion.
Everything you could want to know about arrays in the PHP Documentation.

Parsing JSON output from Perl Script in PHP

I have a PHP file that runs a Perl script, using popen and the perl script outputs the following back to the php
{ 'City' => [ 'LA', 'Chicago', 'NY' ], 'Name' => 'Kevin Bridges', 'Id' => '7075', 'Last-Status-Change' => { 'Time' => 14172911, 'User' => 'kbridge', 'To' => 'LAX', 'From' => 'ORD' }}
I cannot modify the perl script, and I really don't know the contents of it. But it looks like it is outputting JSON. I have tried using json_encode to grab the contents of the output but no success. Can anyone tell me if it is possible to parse this or do I have to manually write a parser?
Convert => to : and ' to ". After that use json_decode to create associative array from the string.
$array = json_decode(str_replace(["=>", "'"], [":", '"'], $a), true);
That's not JSON but is "almost" the PHP [] array syntax, except it uses some {}. You could try:
eval('$array = ' . str_replace(['{','}'], ['[',']'], $output) . ';');
print_r($array);
It does not looks like to be a valid JSON, it seems to be a PERL hash, so i think you gonna need to parse that manually... a simple way to you accomplish that in PHP, it would be to replace the {-} to [] and you can eval that string to be consider an array in PHP

Error when post data with ajax?

When I using ajax post data with struct
And I get data from code here:
$_POST["post"]; => result is 979, that's OK
$_POST["href[href]"]; => result is 0, How to fix it?
Bracket notation is used to create an array entry. Use this instead:
$_POST["href"]["href"];
Calling $_POST["href"] will return an associative array:
array(
'commentID' => 297980913637729,
'href' => 'http://dongcam.vn/t3927'
);
It's a multidimensional array, so:
$_POST["href"]["href"];

How to use json and php

I'm new to JSON, but I have experience in PHP. Can someone explain to me how JSON works, especially with PHP, and EASY way would be nice.
EX: I have a php array like:
array(
array('id' => 1, 'img' => "http.img1.png", 'title' => 'ice cream'),
array('id' => 2, 'img' => "http.img2.png", 'title' => 'silly snail'),
array('id' => 3, 'img' => "http.img3.png", 'title' => 'big bear'),
array('id' => 4, 'img' => "http.img4.png", 'title' => 'Funny cat'),
);
is this fine, or should I alter this array? I want to convert this to a JSON Object. In the php array should there be a parent, and do I have to assign array elements as children, or can each php obj be it's own JSON obj? Thank you!
Just run json_encode on the variable that you want to turn into a json string.
$something = array("test" => array("value", "another value", 4));
echo json_encode($something)
This will produce
{"test":["value","another value",4]}
Also, putting that string into $something = json_decode("{"test":["value","another value",4]}"); will produce back the same array that was passed into json_encode.
Note that JSON is not a programming language; it is a way to represent objects. http://json.org has a complete visual representation of how to use it. JSON's main components are Arrays (surrounded by []) and Objects (surrounded by {}). Arrays are lists of comma separated values (see json.org for how to tell it the types...its pretty simple) while objects are key:value pairs separated by commas between each pair where they key is a string surrounded by quotation marks. Above I created an Object with a key called "test" whose value was an Array with two strings and a number in it.
Use json_encode() for encoding the array, get the array back by using json_decode().

How can i use different string value's in one function?

First i am a beginner in programming in general, i am trying to create a program for using gps locations from Lightroom on a map in googlemaps.
When i use the print the strings below ti the screen i see 5 different value's, this is also what i want, but...
I want to create also 5 different markers on the map this is done by the addMarkerByCoords Function but how can i use the 5 value per strings in the function ?
I have tried array, foreach but i cannot getting to work. The not working part can and probably will be my fault. LOL
print_r ("$Loncoord");
print_r ("$Latcoord");
print_r ("$gui");
//$map->formatOutput = true;
$map->addMarkerByCoords("$Loncoord","$Latcoord","$gui",'<b>Old Chicago</b>');
Can somebody give me a hint ?
To: Jonathan Sampson:
outputs print_r :-5.68166666667, +24.6513888889,IMG_3308,index.html,Landschap
To: Anti Veeranna I removed the " marks (and the program still works), but can you explain why this is better ?
And to the others Thank you very very much for the effort,work and really quick responses.
Assuming that this is PHP, you could us an array of arrays, and then loop.
Something like this:
$items = array(
array(
'long' => 12.34567,
'lat' => 34.56789,
'gui' => '????',
'location' => 'old chicago'
),
...
array(
'long' => 12.34567,
'lat' => 34.56789,
'gui' => '????',
'location' => 'old chicago 5'
)
);
foreach ($items as &$item) {
$map->addMarkerByCoords(
$item['long'],
$item['lat'],
$item['gui'],
$item['location']
);
}
unset($item);
$map->addMarkerByCoords(Array($Loncoord, $Latcoord, $gui, '<b>Old Chicago</b>));
??

Categories