Accessing object property by variable in php - php

Objectives:
I am trying to read certain parts of any json file by letting the user input the desired properties.
Say I have an object that looks like this:
"adverts": [
{
"id": "33655628",
"companyInfo": {
"companyName": "Company A",
"homepage": "http://companya.com",
"companyText": null
},
...
]
I want to access the properties by assigning the property name or "path" by a variable.
Accessing the first level ($item->$_id) works fine but how do I access a nested property companyName directly with by a variable such as
$_name = "companyInfo->companyName";
Ex:
$_repeat = "adverts";
$_id = "id";
$_name = ??????
foreach($data->$_repeat as $item){
var_dump($item->$_id);
var_dump($item->$_name);
}
EDIT:
As clarification: I want this to be universal for any JSON object!
PRELIMINARY SOLUTION:
I got the desired results by looping as suggested by #Carlos:
$_title_a = explode(".",$_title);
$current = $document;
foreach($_title_a as $a){
$current = $current->$a;
}
var_dump($current);
If someone has a better suggestion, I would be glad to hear it. Thanks everybody!

Why do you exactly need this?
All you have to do is:
$jsonData = json_decode($jsonString, true);
echo $jsonData['adverts'][0]['companyInfo']['companyName'];
//or
foreach($jsonData['adverts'] as $advert){
echo $advert['companyInfo']['companyName'];
}

It seems that you have json data with you..you can use below code..
$obj= json_decode($yourJsonData);
print_r($obj);
foreach ($obj as $key => $value) {
$companyinfo = $value['companyInfo']['companyName'];
}
In foreach loop you will get require key and values..this is just a example for you..

Related

If value within Json is equal to set value then return Name [PHP]

So I have a web JSON API and I want to display certain objects from it on my site. Here's my JSON;
{
"descriptions": [
{
"name" = "Jim",
"class" = "3'
},
{
"name" = "luke",
"class" = "2"
},
{
"name" = "Mat",
"class" = "3"
}
I would like to make a list of the students in class 3. Currently, this is what I have to gather and pass the data although I'm not sure how to run the check to see if they're in the class and if so return there name.
$api = "https://students.com";
$json = json_decode(file_get_contents($api ), true);
$students= $json ["descriptions"][0]["class"];
Although that just returns 3 the first class value.
Note
I apologize if there's a similar post but I was unable to find one that answers my simple request. Possibly I'm just not looking in the right place. Thanks in advance
You can use array_filter() also.
$filteredStudent = array_filter($json["description"], function($value) {
return $value["class"] == 3;
});
http://php.net/manual/en/function.array-filter.php
foreach($json["descriptions"] as $value)
{
if($value['class'] == '3')
$names[] = $value['name'];
}
return $names;

merge Array of objects into array with unique object

I have a array of various object, but I need turn this objects into unique object. Below I share my code.
$result = [];
$idiomas = Idioma::all()->toArray();
foreach ($idiomas as $lang) {
$result[] = [
$lang['palavra_chave'] => $lang[$id]
];
}
return response()->json($result);
reponse
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
But I need transform this objects into one, like this
[
{
"INICIAL": "Inicial",
"RELATORIOS": "Relatórios",
"FUNCIONARIO": "Funcionário",
"DATA": "Data",
"ANEXAR_IMAGEM": "Anexar imagem",
"DISCIPLINA": "Disciplina"
}
]
anyone can help me?
$idiomas = Idioma::all()->toArray();
if (count($idiomas)) {
//$result = new stdClass; # wouldn't work without base namespace
$result = new \stdClass;
foreach ($idiomas as $lang) {
$result->{$lang['palavra_chave']} = $lang[$id];
}
return response()->json([$result]);
}
// otherwise
Edit: #Tpojka's answer definitely looks more appropriate. Use the following one only if you can't change the way you retrieve data initially (I'm not familiar enough with Laravel).
The following should work:
// Take your initial JSON
$input = <<<JSON
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
JSON;
// Transform it into a PHP array
$input_as_array = json_decode($input);
// Reduce it into an associative array
$associative_array = array_reduce($input_as_array, function($associative_array, $item) {
return $associative_array += (array)$item;
}, []);
// Encode it back into JSON, as an array
$result = json_encode([$associative_array], JSON_PRETTY_PRINT);

Get {} as an output instead of []

I have service which returns the menu of venues, but if menu is not exist, I should return {} as an output, otherwise ios app cannot parse the response and app destroys.
Now reponse looks like:
{
"response": []
}
I should have
{
"response": {}
}
API services programmed with PHP.
When menu empty url: http://ilovejetset.com/api/v2/menu/index/422
When some menu exist: http://ilovejetset.com/api/v2/menu/index/423
The code for creating response:
in 'after' function:
$this->response->body(json_encode(array('response' => $this->response_json)));
when no menu:
$this->response_json = array();
Check out this page:
Predefined Constants (JSON) More specifically JSON_FORCE_OBJECT
If the data which is deeper than responses needs to be an array then you will need to loop over first encode all of that data, then encode the top layer.
$test = array(
"responses" => array()
);
echo json_encode($test, JSON_FORCE_OBJECT);
If you need an object, then you need to create an object in PHP as well. As long as you're using arrays, PHP will preferably encode them as JSON arrays.
$data = new stdClass;
$data->foo = 'bar';
echo json_encode(array($data));
or:
echo json_encode(array((object)array('foo' => 'bar')));
if you use json_encode this function, you can try to add the option JSON_FORCE_OBJECT as fllows.
<?php
$var = array();
$var['response'] = array();
echo json_encode($var, JSON_FORCE_OBJECT);
$var1 = array();
$var1['response'] = array();
$var1['response']['name'] = 'jediliang';
echo json_encode($var1, JSON_FORCE_OBJECT);
?>
the output looks like this:
{"response":{}}{"response":{"name":"jediliang"}}
For more clarification try this following example
class a {
var $name;
};
$a = new a;
$a->name = array("name"=>"fname");
echo json_encode(array("a"=> $a, "name"=>array("fname","lname")));
Hope it clears all your doubts

decode multiple json object php

I have this jsone that I need to convert in three different objects.
in some php. I know that i have to use json_decode but I only decode the first object , the others 2 object don't.
{
"recorrido":[
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:32",
"globaltime":"00:09",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":1,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
},
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:35",
"globaltime":"00:12",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":2,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
}
],
"user":{
"asunto":"",
"userId":1
},
"Itemout":{
"uploaded":"false",
"isSelected":false,
"id":1,
}
}
what do you sugest? the script must be in php. the object "recorrido" is a multiple array object.
wthout testing it, try somrting like this:
$tempArray = (array)$recorrido; // or how you cal your json object
foreach ($tempArray as $tempJson)
{
$myArray = json_decode($tempJson);
print_r($myArray);
}
You can use hardcode method if you have static json structure:
Show below
$result = json_decode($json);
$recorrido = $result->recorrido;
// And so on
In another way there is a workaround with arrays.
list($arr1, $arr2, $arr3) = json_decode($json, true);
This solution will make you three arrays of data from json.

access a property via string with array in php?

I have a big list of properties that I need to map between two objects, and in one, the value that I need to map is buried inside an array. I'm hoping to avoid hard-coding the property names in the code.
If I have a class like this:
class Product {
public $colors, $sizes;
}
I can access the properties like this:
$props = array('colors', 'sizes');
foreach ($props as $p) {
$this->$p = $other_object->$p;
}
As far as I can tell, if each of the properties on the left are an array, I can't do this:
foreach ($props as $p) {
$this->$p[0]['value'] = $other_object->$p;
}
Is that correct, or am I missing some clever way around this?
(This is in drupal, but I don't really think that matters.)
I believe you can wrap it in curly braces {}:
foreach ($props as $p) {
$this->{$p}[0]['value'] = $other_object->$p;
}
Edit:
Okay. Now my brain turned on. Sorry for the confusing edits.
Also try this:
$props = get_object_vars($this);
foreach ($props as $p) {
$this->{$p}[0]['value'] = $other_object->{$p};
}
It's called variable, variables.
I don't understand your problem. This works:
class Test {
public $prop = "prov value";
}
$arr = array(array("prop"));
$test = new Test();
$test->$arr[0][0] = "new prop value";
var_dump($test);
result:
object(Test)#1 (1) {
["prop"]=>
string(14) "new prop value"
}

Categories