Can't access to json position in foreach - php

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

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,
...
]

array_diff_assoc() argument #1 is not an array php

So I have this object:
[
{
"id":1,
"name":"create-users",
"display_name":"Create user",
"description":"Add new user"
},
{
"id":2,
"name":"edit-user",
"display_name":"Edit user",
"description":"Edit existing user"
},
{
"id":3,
"name":"create-post",
"display_name":"Create post",
"description":"create new post"
},
{
"id":4,
"name":"edit-post",
"display_name":"Edit post",
"description":"edit existing post"
}
]
and this other one:
[
{
"id":3,
"name":"create-post",
"display_name":"Create post",
"description":"create new post"
},
{
"id":4,
"name":"edit-post",
"display_name":"Edit post",
"description":"edit existing post"
}
]
Now I am looping through these two objects in nested foreach loops top compare which of the arrays from the two objects are equal(equal key and value pairs).
Here are the foreach loops:
foreach ($role_perms as $role_perm) {
foreach ($all_perms as $all_perm) {
if (array_diff_assoc($all_perm, $role_perm)) {
$all_perm['check'] = 1;
}
}
}
But I have no idea why I keep getting the error
array_diff_assoc(): Argument #1 is not an array
(on the line of code with the if statement.)
Am I doing something wrong? Thanks for any help
array_diff_assoc() is for comparing arrays. And your data is not.
If you want to use array_diff_assoc() modify your data structure so that you have an array of arrays. For instance:
$your_array = [
[
"id" => 3,
"name"=>"create-post",
"display_name"=>"Create post",
"description"=>"create new post"
],
[
"id"=>4,
"name"=>"edit-post",
"display_name"=>"Edit post",
"description"=>"edit existing post"
]
];
Edited:
As a workaround, cast objects to arrays in case you can't modify your data structure.
$object = new stdClass();
$object->a = 'AAA';
$object->b = 'BBB';
var_dump((array) $object);
Output:
array(2) { ["a"]=> string(3) "AAA" ["b"]=> string(3) "BBB" }
In your case:
foreach ($role_perms as $role_perm) {
foreach ($all_perms as $all_perm) {
if (array_diff_assoc((array) $all_perm, (array) $role_perm)) {
$all_perm['check'] = 1;
}
}
}

How to decode this json with 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;
}

mongodb php get array value

I am trying to get ONE value from a sub document of a stored doc.
a sample document looks like this and I'm trying to get the value "doc2":
{
"_id" : ObjectId("52060cae8b080ed4170063d3"),
"form_id" : "5204c6dca0875b6a1545f436",
"update" : false,
"values" : [{
"5204c71a8b080e6c190000bb" : "doc2"
}, {
"5204c7638b080e6c19006b06" : "that one too"
}, {
"form_id" : "5204c6dca0875b6a1545f436"
}, {
"btn_submit" : "Save"
}]
}
so far my code looks like this:
try {
$connection = new Mongo();
$database = $connection->selectDB('forms');
$collection = $database->selectCollection('instance');
} catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
$value = $collection->findOne(array('_id' =>new MongoId($instid)),array('values.'.$fid));
$instid is passed in and is form_id in the document. And $fid is passed in and is the key in the values array in the document
and I'm getting this:
{ ["_id"]=> object(MongoId)#15 (1)
{ ["$id"]=> "52060cae8b080ed4170063d3" }
["values"]=>
{ [0]=> { ["5204c71a8b080e6c190000bb"]=> "doc2" }
[1]=> array(0) { }
[2]=> array(0) { }
[3]=> array(0) { }
} }
Thanks in advance for any assistance.
You are getting data in form of multidimensional Array, So you should use
print_r($value['values']['0']);
This will return
Array ( [5204c71a8b080e6c190000bb] => doc2 )
And if you only want to echo out doc2 then you can use foreach statement
foreach($value['values']['0'] as $x)
{
echo $x;
}

Using json_encode on objects in PHP (regardless of scope)

I'm trying to output lists of objects as json and would like to know if there's a way to make objects usable to json_encode? The code I've got looks something like
$related = $user->getRelatedUsers();
echo json_encode($related);
Right now, I'm just iterating through the array of users and individually exporting them into arrays for json_encode to turn into usable json for me. I've already tried making the objects iterable, but json_encode just seems to skip them anyway.
edit: here's the var_dump();
php > var_dump($a);
object(RedBean_OODBBean)#14 (2) {
["properties":"RedBean_OODBBean":private]=>
array(11) {
["id"]=>
string(5) "17972"
["pk_UniversalID"]=>
string(5) "18830"
["UniversalIdentity"]=>
string(1) "1"
["UniversalUserName"]=>
string(9) "showforce"
["UniversalPassword"]=>
string(32) ""
["UniversalDomain"]=>
string(1) "0"
["UniversalCrunchBase"]=>
string(1) "0"
["isApproved"]=>
string(1) "0"
["accountHash"]=>
string(32) ""
["CurrentEvent"]=>
string(4) "1204"
["userType"]=>
string(7) "company"
}
["__info":"RedBean_OODBBean":private]=>
array(4) {
["type"]=>
string(4) "user"
["sys"]=>
array(1) {
["idfield"]=>
string(2) "id"
}
["tainted"]=>
bool(false)
["model"]=>
object(Model_User)#16 (1) {
["bean":protected]=>
*RECURSION*
}
}
}
and here's what json_encode gives me:
php > echo json_encode($a);
{}
I ended up with just this:
function json_encode_objs($item){
if(!is_array($item) && !is_object($item)){
return json_encode($item);
}else{
$pieces = array();
foreach($item as $k=>$v){
$pieces[] = "\"$k\":".json_encode_objs($v);
}
return '{'.implode(',',$pieces).'}';
}
}
It takes arrays full of those objects or just single instances and turns them into json - I use it instead of json_encode. I'm sure there are places I could make it better, but I was hoping that json_encode would be able to detect when to iterate through an object based on its exposed interfaces.
All the properties of your object are private. aka... not available outside their class's scope.
Solution for PHP >= 5.4
Use the new JsonSerializable Interface to provide your own json representation to be used by json_encode
class Thing implements JsonSerializable {
...
public function jsonSerialize() {
return [
'something' => $this->something,
'protected_something' => $this->get_protected_something(),
'private_something' => $this->get_private_something()
];
}
...
}
Solution for PHP < 5.4
If you do want to serialize your private and protected object properties, you have to implement a JSON encoding function inside your Class that utilizes json_encode() on a data structure you create for this purpose.
class Thing {
...
public function to_json() {
return json_encode(array(
'something' => $this->something,
'protected_something' => $this->get_protected_something(),
'private_something' => $this->get_private_something()
));
}
...
}
A more detailed writeup
In PHP >= 5.4.0 there is a new interface for serializing objects to JSON : JsonSerializable
Just implement the interface in your object and define a JsonSerializable method which will be called when you use json_encode.
So the solution for PHP >= 5.4.0 should look something like this:
class JsonObject implements JsonSerializable
{
// properties
// function called when encoded with json_encode
public function jsonSerialize()
{
return get_object_vars($this);
}
}
In RedBeanPHP 2.0 there is a mass-export function which turns an entire collection of beans into arrays. This works with the JSON encoder..
json_encode( R::exportAll( $beans ) );
Following code worked for me:
public function jsonSerialize()
{
return get_object_vars($this);
}
I didn't see this mentioned yet, but beans have a built-in method called getProperties().
So, to use it:
// What bean do we want to get?
$type = 'book';
$id = 13;
// Load the bean
$post = R::load($type,$id);
// Get the properties
$props = $post->getProperties();
// Print the JSON-encoded value
print json_encode($props);
This outputs:
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
}
Now take it a step further. If we have an array of beans...
// An array of beans (just an example)
$series = array($post,$post,$post);
...then we could do the following:
Loop through the array with a foreach loop.
Replace each element (a bean) with an array of the bean's properties.
So this...
foreach ($series as &$val) {
$val = $val->getProperties();
}
print json_encode($series);
...outputs this:
[
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
},
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
},
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
}
]
Hope this helps!
I usually include a small function in my objects which allows me to dump to array or json or xml. Something like:
public function exportObj($method = 'a')
{
if($method == 'j')
{
return json_encode(get_object_vars($this));
}
else
{
return get_object_vars($this);
}
}
either way, get_object_vars() is probably useful to you.
$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;
Here is my way:
function xml2array($xml_data)
{
$xml_to_array = [];
if(isset($xml_data))
{
if(is_iterable($xml_data))
{
foreach($xml_data as $key => $value)
{
if(is_object($value))
{
if(empty((array)$value))
{
$value = (string)$value;
}
else
{
$value = (array)$value;
}
$value = xml2array($value);
}
$xml_to_array[$key] = $value;
}
}
else
{
$xml_to_array = $xml_data;
}
}
return $xml_to_array;
}
for an array of objects, I used something like this, while following the custom method for php < 5.4:
$jsArray=array();
//transaction is an array of the class transaction
//which implements the method to_json
foreach($transactions as $tran)
{
$jsArray[]=$tran->to_json();
}
echo json_encode($jsArray);

Categories