How to decode this json with php? - php

I have this json code:
$cars = '{
"CarBenz":
[
{
"Car": "Benz",
"Color": "Black"
}
]
}';
$json = json_decode($cars , true);
how to print Benz in screen?
print $json['Car'];
$json['Car'] nothing show anything.

To see the type of a variable (and how an object or array is built up) you can use var_dump($json).
In this case, that will give:
array(1) {
["CarBenz"]=>
array(1) {
[0]=>
array(2) {
["Car"]=>
string(4) "Benz"
["Color"]=>
string(5) "Black"
}
}
}
So you need to do $json['CarBenz'][0]['Car'].

First you can var_dump your decoded json string and you can see the array with the structure.
I think you forgot to access the CarBenz element first.
echo $json['CarBenz'][0]['Car'];
If you need all elements in CarBenz you have to iterate over them. Something like that:
foreach($json['CarBenz'] as $car) {
echo $car;
}

Related

Format array of objects for possible json output for Postman/GET requests

So I can't seem to figure this out, so I'm reaching out to see if someone might be able to help me.
Please let me know what the best output is so that I could use GET to retrieve clean data for the endpoint that I've created.
I have the following method:
function instagram_posts(): bool|string
{
if (!function_exists('is_plugin_active')) {
include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}
if (!is_plugin_active('fh-instagram/autoload.php')) {
return false;
}
if (empty($items = Instagram::get_items_for_api(50))) {
return false;
}
var_dump($items);
var_dump(json_encode($items));
return json_encode($items);
}
var_dump($items); gives me the following output:
array(50) {
[0]=>
object(Plugin\Instagram\Item)#976 (7) {
["id":"Plugin\Instagram\Item":private]=>
}
[1]=>
object(Plugin\Instagram\Item)#1030 (7) {
["id":"Plugin\Instagram\Item":private]=>
string(17) "17842233125750202"
}
}
When I run var_dump(json_encode($items)); I get the following output:
string(151) "[{},{}]"
How can I convert my array of objects so that it can transform it to json and then use it within Postman? This is what it currently looks like in Postman:
array(50) {
[0]=>
object(Plugin\Instagram\Item)#973 (7) {
["id":"Plugin\Instagram\Item":private]=>
string(17) "17992874035441353"
}
[1]=>
object(Plugin\Instagram\Item)#1027 (7) {
["id":"Plugin\Instagram\Item":private]=>
string(17) "17842233125750202"
}
}
It should be outputted such as:
[
{"id": etc..}
]
All help will be appreciated!
The instagram_posts method is being use below:
add_action('rest_api_init', function () {
register_rest_route( 'instagram', '/posts/', [
'methods' => 'GET',
'callback' => 'instagram_posts',
]);
});
So I can use Postman to access the endpoint: http://headlesscms.com.local/wp-json/instagram/posts
Since the property you want is private, it won't be included in the results of json_encode(). Only public properties will.
You need to create a multidimensional array with the structure you want and encode that.
// This is the new array we will push the sub arrays into
$results = [];
foreach($items as $item) {
$results[] = ['id' => $item->get_id()];
}
return json_encode($results);
This will give you a json structure that looks like:
[
{
"id": 1
},
{
"id": 2
},
...
]
Alternative format
If you only want a list of id's, you might not need to create a multidimensional array, but rather just return a list of ids.
In that case, do this:
$results = [];
foreach ($items as $item) {
$results[] = $item->get_id();
}
return json_encode($results);
That would give you:
[
1,
2,
...
]

Add array in array of arrays

I have a $_SESSION index called "items".
Just like this:
$_SESSION['items'];
When user click to add item I check if $_SESSION['items'] exists. If exists, then insert the item, if not, create and insert. Ok.
So I coded this solution:
$newItem = array(
'id'=>$this->getId(),
'red'=>$this->getRef()
);
if(isset($_SESSION['items'])) {
array_push($_SESSION['items'],$newItem);
} else {
$_SESSION['items'] = $newItem;
}
Ok.
The problem is:
If the "else" occurs, the $newItem array is pushed into $_SESSION['items'] with this structure:
{
0: {
id: "1",
ref: "0001",
}
}
Exactly as I was expecting.
But if the "if" statement occurs, my $_SESSION['item'] looses the new indexes and I get a structure like this:
{
0: {
id: "1",
ref: "0001",
},
id: "2",
ref: "0001",
}
As you can see, the new item is not set as array...
If I add more itens, the issue affects only the last item added...
What I am doing wrong?
Change your code to the following:
if (isset($_SESSION['items'])) {
array_push($_SESSION['items'],$newItem);
} else {
$_SESSION['items'] = [];
array_push($_SESSION['items'], $newItem);
}
Now, all the $newItems will be pushed in to an actual array.
Output
array(1) {
["items"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(2) "id"
["ref"]=>
string(3) "ref"
}
[1]=>
array(2) {
["id"]=>
string(4) "id-2"
["ref"]=>
string(5) "ref-2"
}
}
}
Live Example
Repl - Dummy data used
Your array_push here seems to be problem, because when you are pushing the array in $_SESSION[‘items’] it takes $newItem array elements and pushes them in the $_SESSION[‘items’]
If you can do as below then it should work
$newItem = array(
'id'=>$this->getId(),
'red'=>$this->getRef()
);
$_SESSION['items'][]= $newItem;

Can't access to json position in foreach

I'm trying to get all values of this JSON:
{"_links":[{"self":"http://api.football-data.org/alpha/soccerseasons/394/teams"},{"soccerseason":"http://api.football-data.org/alpha/soccerseasons/394"}],"count":18,"teams":[{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/5"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/5/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/5/players"}},"name":"FC Bayern München","code":"FCB","shortName":"Bayern","squadMarketValue":"551,250,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/c/c5/Logo_FC_Bayern_München.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/7"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/7/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/7/players"}},"name":"Hamburger SV","code":"HSV","shortName":"HSV","squadMarketValue":"71,100,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/6/66/HSV-Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/16"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/16/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/16/players"}},"name":"FC Augsburg","code":"FCA","shortName":"Augsburg","squadMarketValue":"48,550,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/b/b5/Logo_FC_Augsburg.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/9"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/9/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/9/players"}},"name":"Hertha BSC","code":"BSC","shortName":"Hertha","squadMarketValue":"63,700,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/8/81/Hertha_BSC_Logo_2012.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/3"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/3/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/3/players"}},"name":"Bayer Leverkusen","code":"B04","shortName":"Leverkusen","squadMarketValue":"177,100,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/9/95/Bayer_04_Leverkusen_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/2"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/2/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/2/players"}},"name":"TSG 1899 Hoffenheim","code":"TSG","shortName":"Hopenhoam","squadMarketValue":"118,200,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/e/e7/Logo_TSG_Hoffenheim.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/55"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/55/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/55/players"}},"name":"SV Darmstadt 98","code":"DAR","shortName":"Darmstadt","squadMarketValue":"12,450,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/8/87/Svdarmstadt98.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/8"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/8/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/8/players"}},"name":"Hannover 96","code":"H96","shortName":"Hannover","squadMarketValue":"74,500,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/c/cd/Hannover_96_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/15"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/15/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/15/players"}},"name":"1. FSV Mainz 05","code":"M05","shortName":"Mainz","squadMarketValue":"75,200,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/0/0b/FSV_Mainz_05_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/31"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/31/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/31/players"}},"name":"FC Ingolstadt 04","code":"FCI","shortName":"Ingolstadt","squadMarketValue":"18,600,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/5/55/FC-Ingolstadt_logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/12"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/12/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/12/players"}},"name":"Werder Bremen","code":"SVW","shortName":"Bremen","squadMarketValue":"52,600,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/b/be/SV-Werder-Bremen-Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/6"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/6/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/6/players"}},"name":"FC Schalke 04","code":"S04","shortName":"Schalke","squadMarketValue":"208,850,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/6/6d/FC_Schalke_04_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/4"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/4/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/4/players"}},"name":"Borussia Dortmund","code":"BVB","shortName":"Dortmund","squadMarketValue":"317,800,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/6/67/Borussia_Dortmund_logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/18"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/18/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/18/players"}},"name":"Bor. Mönchengladbach","code":"BMG","shortName":"M'gladbach","squadMarketValue":"130,450,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/c/cc/Borussia_Moenchengladbach_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/11"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/11/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/11/players"}},"name":"VfL Wolfsburg","code":"WOB","shortName":"Wolfsburg","squadMarketValue":"206,350,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/b/bc/VfL_Wolfsburg_Logo_weiß.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/19"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/19/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/19/players"}},"name":"Eintracht Frankfurt","code":"SGE","shortName":"Eintr. Frankfurt","squadMarketValue":"69,050,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/0/04/Eintracht_Frankfurt_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/10"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/10/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/10/players"}},"name":"VfB Stuttgart","code":"VFB","shortName":"Stuttgart","squadMarketValue":"89,050,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/commons/a/ab/VfB_Stuttgart_Logo.svg"},{"_links":{"self":{"href":"http://api.football-data.org/alpha/teams/1"},"fixtures":{"href":"http://api.football-data.org/alpha/teams/1/fixtures"},"players":{"href":"http://api.football-data.org/alpha/teams/1/players"}},"name":"1. FC Köln","code":"EFFZEH","shortName":"Köln","squadMarketValue":"42,150,000 €","crestUrl":"http://upload.wikimedia.org/wikipedia/de/1/16/1._FC_Köln.svg"}]}
I've created this decoder
$decoded = json_decode($response,true);
so I perform a foreach to iterate through the object:
foreach($decoded['teams'] as $team => $value)
{
var_dump($decoded['_links']['self']['href');
}
but this code return a NULL object. I want get this content:
{"_links":[{"self":"http://api.football-data.org/alpha/soccerseasons/394/teams"},
json structure:
{
"_links": {
"self": { "href": "http://api.football-data.org/alpha/teams/19" },
"fixtures": { "href": "http://api.football-data.org/alpha/teams/19/fixtures" },
"players": { "href": "http://api.football-data.org/alpha/teams/19/players" }
},
"name": "Eintracht Frankfurt",
"code": "SGE",
"shortName": "Eintr. Frankfurt",
"squadMarketValue": "75.475.000 ?",
"crestUrl": "http://upload.wikimedia.org/wikipedia/commons/0/04/Eintracht_Frankfurt_Logo.svg"
}
What I doing wrong?
From your comment, we can see
array(3) {
["_links"]=> array(2) {
[0]=> array(1) {
["self"]=> string(58) "api.football-data.org/alpha/soccerseasons/394/teams"; }
[1]=> array(1) {
["soccerseason"]=> string(52) "api.football-...";}
}
So, to get your "self" value, you must access $decoded["_links"][0]["self"]
You are using $decoded var in place of $value. It should be like this:
foreach($decoded['teams'] as $team => $value)
{
var_dump($value['_links']['self']['href']);
}
Update
To get self link of json you don't need to iterate over teams. You should iterate over _links like that:
foreach($decoded['_links'] as $link)
{
var_dump(reset($link));
}
To get only first link (only if document structure will never change) you need only one line:
var_dump($decoded['_links'][0]['self']);

Get all object from a "group" in PHP from JSON array

I'm trying to catch all objects in PHP from a JSON array, I need all the objects that will appear under ["Elements"]. So how would this be possible if I:
1.) Don't know the "name" of the object and don't know the content inside it.
2.) What I would like to achieve is to get the first objects value inside Elements, and then get the "content" inside of it, regardless of the names (there could be multiple objects)
Here is a var_dump of the JSON:
object(stdClass)#1 (1) {
["Canvas"]=>
array(1) {
[0]=>
["Elements"]=>
object(stdClass)#18 (2) {
["textHolder2"]=>
object(stdClass)#19 (1) {
["textContent"]=>
string(12) "Text to edit"
}
["textHolder1"]=>
object(stdClass)#20 (1) {
["textContent"]=>
string(12) "Text to edit"
}
}
}
}
}
Use foreach.
$json = json_decode( $input, true );
$elems = $json['canvas']['Elements'];
foreach( $elems as $key => $value ) {
echo "{$key} is an array/object:\n";
echo var_dump( $value );
}
You could use array_keys() if you need to know what keys are inside $value or you could another foreach loop, but I am assuming you will have at least some clue what keys could be in $value.

Passing Array from Model to Controller to View in CodeIgniter

I have a model that sends an error response to the controller in CodeIgniter that then is passed to the view which is just a JSON encoder. Here is the array from the model.
return $posts[] = array('complete'=>0,'error'=>1003, 'message'=>'Username already exists');
The issue I am having is that I need those square brackets after the $posts variable because sometimes I need an array of errors. However when I pass the single array to the view it encodes the JSON without the square brackets but when I have multiple arrays it includes the square brackets, I need the square brackets in the JSON every time. Here is the Controller...
$data['data'] = $this->logins_model->signup($post_data);
$this->load->view('json', $data);
Here is the view...
header('Content-type: application/json');
$response['response'] = $data;
echo json_encode($response);
I need the JSON response to look like this
{
"response": [
{
"complete": 0,
"error": 1003,
"message": "Username already exists"
}
]
}
NOT THIS!
{
"response": {
"complete": 0,
"error": 1003,
"message": "Username already exists"
}
}
Since you want to get array in json you should be having it in php array as well (i.e. data-structures should meet). So $response['response'] = $data; should be $response['response'] = array($data);
In your example var_dump($response); gives:
array(1) {
["response"]=>
array(3) {
["complete"]=>
int(0)
["error"]=>
int(1003)
["message"]=>
string(23) "Username already exists"
}
}
As you see $response['response'] is an object for json.
When you replace $response['response'] = $data; with $response['response'] = array($data); your data-structure, which you want to convert in json will become:
array(1) {
["response"]=>
array(1) {
[0]=>
array(3) {
["complete"]=>
int(0)
["error"]=>
int(1003)
["message"]=>
string(23) "Username already exists"
}
}
}
That will give you desired output because json_encode will expect that there might be another items in $response['response'].
Demo
Edit
Your model should be returning one dimensional array. For example:
return array('complete'=>0,'error'=>1003, 'message'=>'Username already exists');
And you should assign it to another array that is holding all error messages:
$data['data'][] = $this->logins_model->signup($post_data);
$this->load->view('json', $data);
Demo 2
In your view define $post as an array and remove tha square brackets from there. To check your results in view use print_r instead of echo. Which will show exactly how many data is retrieved.

Categories