Dynamically parse multiple json array objects with php - php

I have a json file as below name "brands.json"
{
"title":"List of brands",
"version" : 1,
"nike": [
{"type":"shoes","size":10,"color":"black"},
{"type":"shirt","size":"S","color":"black"}
],
"converse": [
{"type":"shoes","size":10,"color":"red"},
{"type":"backpack","size":"N/A","color":"red"}
],
"champion": [
{"type":"shoes","size":10,"color":"blue"},
{"type":"pants","size":"M","color":"grey"}
]
}
I looked at some example online and get this piece of code
<?php
$read = file_get_contents("report.json");
$json = json_decode($read, true);
foreach($json as $key => $val){
if(is_array($val)){
echo "$key : <br>";
foreach($key as $k => $v){
echo "$k => $v<br>";
}
}
else {
echo "$key => $val<br>";
}
}
?>
I would be able to print out
title => List of brands
version => 1
nike :
converse :
champion :
But I would like to get the array inside of those brands. I was thinking of having a foreach loop inside the if statement. However, it returns errors
nike : Warning: Invalid argument supplied for foreach().
Some resources suggested to do something like $json->nike as $item => $v but that will be redundant since I also have converse and champion arrays. If someone could direct me to a good resource or provide a code example, it'd be very much appreciated.
Expected table
Nike:
type | size | color
shoes| 10 | black
shirt| S | black

Create function that buffers output and display it
$read = '{
"title":"List of brands",
"version" : 1,
"nike": [
{"type":"shoes","size":10,"color":"black"},
{"type":"shirt","size":"S","color":"black"}
],
"converse": [
{"type":"shoes","size":10,"color":"red"},
{"type":"backpack","size":"N/A","color":"red"}
],
"champion": [
{"type":"shoes","size":10,"color":"blue"},
{"type":"pants","size":"M","color":"grey"}
]
}';
$json = json_decode($read, true);
// this function will run recursively
function display($val){
// create output buffer variable
$output = "";
// check is array or not
if(is_array($val)){
// check is multimensional or not
if(isset($val[0])){
foreach($val as $v){
$output .= "<br/>".display($v);
}
}else{
foreach($val as $k => $v){
$output .= $k." => ".display($v)."<br/>";
}
}
}else{
// append output if it just a value
$output .= $val;
}
return $output;
}
echo display($json);
?>
Preview
https://code.sololearn.com/wkeim4HQO9zP#php

Related

Problem with update database from API in Laravel PHP

I have a database of items, now I need to update the pictures in 10,000 records in the database, I make an API request, I receive an answer, but I just cannot process the answer correctly.
I received result:
{"result":{"items":{"★ StatTrak™ Bowie Knife | Safari Mesh (Battle-Scarred)":{"actions":[{"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D751048845621896210","name":"Inspect in Game..."}],"background_color":null,"commodity":false,"descriptions":[{"app_data":"","type":"html","value":"Exterior: Battle-Scarred"},{"app_data":"","color":"#99CCFF","type":"html","value":"This item features StatTrak™ technology, which tracks certain statistics when equipped by its owner."},{"app_data":"","color":"#CF6A32","type":"html","value":"This item tracks Confirmed Kills."},{"app_data":"","type":"html","value":"This full-tang sawback Bowie knife is designed for heavy use in brutal survival situations. It has been spray-painted using mesh fencing and cardboard cutouts as stencils.\n\n<i>A predator is a predator, no matter the environment</i>"}],"icon_url":"-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpovbSsLQJfwObaZzRU7dCJlo-cnvLLIKvum25C4Ppli-f-_Yn0nk36-EZrYjz2cNedIVRqMFCE_VO3xOfqgpfutJWfySRi7nRw7Snan0DmhQYMMLIiC3JRKA"
And i need compare the name, and write in database icon_url value.
But always i received error:
Undefined array key "items" in:
foreach ($prices['items'] as $key => $price) {
$newPrices[$key] = $price['icon_url'];
}
My code:
public function update_information()
{
$prices = json_decode(file_get_contents('https://api.hexa.one/market/items/730?key=O2XDN99XN45XY5EN83CEP3ZZ8X5WDRY4'), true);
if (!$prices['result']) {
dd('Error');
}
$newPrices = [];
foreach ($prices['items'] as $key => $price) {
$newPrices[$key] = $price['icon_url'];
}
$totalUpdated = 0;
foreach (AllItem::query()->get() as $itemDB) {
$fullName = $itemDB->market_hash_name;
if( $itemDB->exterior ) {
$fullName = $itemDB->market_hash_name . '(' . $itemDB->exterior . ')';
}
if (!isset($newPrices[$fullName])) {
continue;
}
$itemDB->update(['image' => $newPrices[$fullName]]);
$totalUpdated++;
$itemDB->save();
$totalUpdated++;
}
dd('done. Updated: ' . $totalUpdated);
}
How i can fix it? Hope for your help!
You forgot the result. The items key is in the result.
array:1 [
"result" => array:2 [
"items" => array:17990 [
....
]
"updated" => 1618501391
]
]
So, you have to replace it with:
foreach ($prices['result']['items'] as $key => $price) {
...
}

PHP list array and get value

I have some difficulties with PHP Arrays. I'm trying to foreach some values, order them with array_multisort and foreach them again so I can create some kind of code.
So what I'm doing is, I'm passing json object as:
"options": [
{"key": "Ships From", "value": "Russia"},
{"key": "Color", "value": "Green"},
{"key": "Size", "value": "M"},
{"key": "Material", "value": "Flex"}
],
So this is received from frontend, and I'm foreaching them like so:
public function findAttribute($product_id, $values)
{
$array = array();
foreach ($values as $key => $value) {
$getAttr = $this->attribute($value['key']);
$getAttrValue = $this->attributeValue($getAttr->id, $value['value']);
$code = $getAttr['label'] . '=' . $getAttrValue['value'];
$collection = array_push($array, array($getAttr->default_order, $code));
}
array_multisort($array, SORT_ASC);
}
As you can see I have $getAttr and $getAttrValue, that selects values from database, in order to get default_order (integer) so I can sort them with multisort.
So actually this code works as expected, and when I write (after multisort) like:
foreach($array as $key => $value){
echo $value[1] .'/';
}
I have expected value, but when I call that function it gives me that it returns NULL, if I change echo to return, I have only first array. If I try like
foreach($array as $key => $value){
$code = $value[1] .'/';
}
return $code;
No success as well.
What should I do?
Because in each iteration you assign a new value to $code so you will only get the last $value [1] in the array (after arranged).
If you want to return a string concatenating all values, you could do as this:
$code = '';
foreach($array as $key => $value){
$code .= $value[1] .'/';
}
return $code;
$code = array();
foreach($array as $key => $value){
$code = $value[$key] .'/';
}
return $code;
Implement your code i hope that will work.

Trying to loop and display a JSON file with PHP

I have a JSON file that has an array inside. I want to loop inside each element of the JSON and display it. I can succesfully do it but I want when using the foreach loop refer to the field like this: $value["pessoa_id"];
When I'm doing like this I get it to display but after displaying it gets a message: "Notice: Undefined index: nome", like it was trying to access it again.
This is the JSON file:
{"Clientes": {
"Pessoa": [
{"pessoa_id" : 1, "nome": "INDUSTRIAL JAVARI LTDA", "endereco": "ENGENHO SANTA TERESA"},
{"pessoa_id" : 2, "nome": "AGROISA-AGRO IND. TRAVESSIA S/A", "endereco": "FAZENDA TRAVESSIA S/N"}
],
"Clientes": [
{"cliente_id" : 1, "loja" : 1, "cliente" : 1, "tpcli": "J", "pontoref": ""},
{"cliente_id" : 2, "loja" : 1, "cliente" : 2, "tpcli": "J", "pontoref": ""}
]
}
}
And the php code:
$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
foreach ($json as $key => $value){
foreach ($value as $key => $val){
foreach ($val as $key => $v){
echo $v["nome"] . " " . $v["endereco"];
echo "<br>";
}
}
}
I want to be able to in one foreach see if it's a "Pessoa" or "Clientes" and loop throught it by getting the fields by the name.
You also iterate over the 2nd array Clientes. You could access the array directly and only iterate over that data:
$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
$pessoa = $json["Clientes"]["Pessoa"];
foreach ($pessoa as $key => $value){
echo $value["nome"] . " " . $value["endereco"];
echo "<br>";
}
Update:
If you need/want to loop over the whole data-set like you did in your question, you can check if you are in the correct element of the object and only than iterate and output the data.
$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
foreach ($json as $key1 => $value){
if ($key1 == "Clientes") {
foreach ($value as $key2 => $val){
if ($key2 == "Pessoa") {
foreach ($val as $key3 => $v){
echo $v["nome"] . " " . $v["endereco"];
echo "<br>";
}
}
}
}
}

get index of json key using php

I want to find index of key from json array similar to this question Get index of a key in json
but i need the solution using php.
here is my json (partial data)
{
"currentOver":{
"events":[]
},
"matchString":"",
"currentPlayer":5,
"previousOvers":[],
"innings":[],
"scorecards":[
{
"batting":{
"players":[
{"id":16447,"name":"Rahul Roy"},
{"id":12633,"name":"Sijal Thomas"},
{"id":16446,"name":"Mohammed Reza"},
{"id":16509,"name":"Asif Khan"},
{"id":12633,"name":"Koyel Dijesh"},
{"id":16468,"name":"Shahrook"},
{"id":64691,"name":"Shafiq"},
{"id":6518,"name":"Ubaidulah"}
]
}
}
]
}
and php
foreach ($read_json->scorecards->batting->players as $batsmen => $val) {
if($val == 5) { // if batsman index is 5 then display his name
$name = $batsmen->name;
echo "<div>$name</div>\n";
}
}
Please help me to solve this issue.Thanks in advance.
I think this would suffice your requirement
http://codepad.org/XQDCKAsB
Find the code sample below as well.
$json = '{"currentOver":{"events": []},"matchString":"","currentPlayer":5,"previousOvers":[],"innings":[],"scorecards":[{"batting":{"players":[{"id":16447,"name":"Rahul Roy"},{"id":12633,"name":"Sijal Thomas"},{"id":16446,"name":"Mohammed Reza"},{"id":16509,"name":"Asif Khan"},{"id":12633,"name":"Koyel Dijesh"},{"id":16468,"name":"Shahrook"},{"id":64691,"name":"Shafiq"},{"id":6518,"name":"Ubaidulah"}]}}]}';
$arr = json_decode($json);
echo '<pre>';
$currentPlayer = $arr->currentPlayer;
echo $arr->scorecards[0]->batting->players[$currentPlayer-1]->name;
Try this code.
$info = json_decode('json string');
$currentPlayer = $info->currentPlayer;
$batsman = $info->scorecards[0]->batting->players[$currentPlayer];
echo "<div>{$batsman->name}</div>\n";
Also, note that arrays in PHP are zero-based. If currentPlayer index in json data is based on 1 (rare case, but it exists sometimes) you will ned to use
$batsman = $info->scorecards[0]->batting->players[$currentPlayer - 1];
to get right item from array.
If you just want to fix your foreach
$read_json->scorecards->batting should become $read_json->scorecards[0]->batting
if($val == 5) should become if($batsmen == 5)
$name = $batsmen->name; should become $name = $val->name;
You need to use json_decode and array_keys for the array keys from the json.
$json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
$result = json_decode ($json, true);
$keys = array_keys($result);
print_r($keys); //Array ( [0] => key1 [1] => key2 [2] => key3 )
In Php, You can use the code below, if you wan to fix it using foreach loop
foreach($json->entries as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
please have a look following code
$json=json_decode($data)->scorecards[0]->batting->players;
foreach ($json as $key => $value) {
if($key==5){
echo $value->name ;
}
}
You can do it using converting JSON string to Array
$json_str = '{
"currentOver":{
"events":[]
},
"matchString":"",
"currentPlayer":5,
"previousOvers":[],
"innings":[],
"scorecards":[
{
"batting":{
"players":[
{"id":16447,"name":"Rahul Roy"},
{"id":12633,"name":"Sijal Thomas"},
{"id":16446,"name":"Mohammed Reza"},
{"id":16509,"name":"Asif Khan"},
{"id":12633,"name":"Koyel Dijesh"},
{"id":16468,"name":"Shahrook"},
{"id":64691,"name":"Shafiq"},
{"id":6518,"name":"Ubaidulah"}
]
}
}
]
}';
Decode your JSON string using "json_decode" and you get array
$json_decode_str = json_decode($json_str, true);
Now using foreach you can do anything
if($json_decode_str['scorecards']){
foreach($json_decode_str['scorecards'] as $scorecard){
$player_index = 1;
if($scorecard['batting']['players']){
foreach($scorecard['batting']['players'] as $player){
if($player_index == 5){
echo $player['name'];
}
$player_index++;
}
}
}
}
Maybe this one help you :)

PHP echo JSON nested array values

I want to echo all expanded_url and urls. echo $name prints results . echo $value doesn't print anything because of nested array. How do I echo all values?
$json ='{ "results" : [ { "entities" :
[ { "urls" : [ { "expanded_url" : "http://www.google.com",
"url" : "http://t.co/WZnUf68j"
}, { "expanded_url" : "http://www.facebook.com",
"url" : "http://t.co/WZnUf68j"
}, { "expanded_url" : "http://www.twitter.com",
"url" : "http://t.co/WZnUf68j"
} ] } ],
"from_user" : "A-user-name",
"from_user_id" : 457304735,
"text" : "Ich R U #BoysNoize #SuperRola"
} ] }';
# $json_array = (array)(json_decode($json));
$data = json_decode($json,true);
foreach($data as $name => $value){
echo $name.'<br>';
echo $value; // NOT WORKING - HOW TO ECHO ALL VALUES
}
You can do that with
$data = json_decode($json,true);
foreach($data["results"][0]["entities"][0]["urls"] as $value){
echo $value['expanded_url']."\n";
echo $value['url']."\n";
}
Since it's a multidimensional array, you can loop through the various levels to reach where you want.
foreach($data['results'] as $item) {
foreach($item['entities'] as $urls) {
foreach($urls['urls'] as $element) {
echo "expanded_url: {$element['expanded_url']} \n";
echo "url: {$element['url']} \n";
}
}
}
Note: The reason I've done the various foreach loops is due to the fact that there may be different results or different entities, so it's better to loop, than to do foreach($data["results"][0]["entities"][0]["urls"] as $value)
Example

Categories