PHP Parsing JSON to HTML Table multi dimensional arrays - php

I have the following JSON Data:
{
"tables": [
{
"name": "PrimaryResult",
"columns": [
{
"name": "TimeGenerated",
"type": "datetime"
},
{
"name": "Computer",
"type": "string"
}
],
"rows": [
[
"2022-12-03T21:58:48.519866Z",
"DESKTOP-KAFCPRF"
],
[
"2022-12-03T21:58:48.5198773Z",
"DESKTOP-KAFCPRF"
]
]
}
]
}
I'm using this to and trying to find a way to parse the columns as tables headers(TH) and the row data as(TR).
This is what I have:
$jsonObjs = json_decode($data, true);
echo "<pre>" . var_dump($jsonObjs) . "</pre>";
foreach($jsonObjs as $a){
foreach($a[0] as $b) {
foreach($b[1] as $key => $value){
echo $key . " : " . $value . "<br />";
}
}
}
but my results are coming up like:
name : Computer
type : string
0 : 2022-12-03T21:58:48.5198773Z
1 : DESKTOP-KAFCPRF

Here is a loop that will go through the columns and rows. From here it's fairly simple to adjust the logic for building a table. If you need any further help, let me know.
foreach($jsonObjs["tables"] as $a)
{
// Columns
foreach($a["columns"] as $key => $value)
{
$cName = $value["name"];
$cType = $value["type"];
echo("Column name is: ".$cName);
echo("Column type is: ".$cType);
}
// Rows:
foreach($a["rows"] as $key => $value)
{
$rValue1 = $value[0];
$rValue2 = $value[1];
echo("Row: " . $rValue1 . " | " . $rValue2);
}
}

Related

PHP - Array Search Not Returning Anything

Currently working on a project in C but I have to generate a large struct which I figured would generate in PHP since I'm more familiar with PHP.
I have 2 arrays. The first one is quite simple (is way larger than this but I assume this is enough to replicate the issue):
$vehicles = [
'vehicleSuper' => [ "adder", "autarch", "banshee2", "bullet" ],
'vehicleSport' => [ "alpha", "banshee", "bestiagts", "blista2" ],
//...
];
The second array looks like this:
$textures = [
'candc_apartments' => [
"limo2_b", "limo2",
],
'candc_default' => [
"marshall_flag18_b", "mesa_b", "rentbus", "marshall_flag21_b", "crusader", "boxville4", "buzzard_b", "dukes2_b", "dukes",
],
'lgm_default' => [
"hotknife", "coquette", "voltic_tless", "vacca", "infernus", "cogcabri_b", "stinger_b", "banshee_b", "ztype", "ninef", "jb700", "superd", "monroe_b", "rapidgt2_b", "khamel", "comet2_b", "cheetah_b", "rapidgt_b", "stinger", "carbon_b", "surano_convertable_b", "rapidgt2", "infernus_b", "jb700_b", "ninef_b", "stingerg", "superd_b", "bullet_b", "ztype_b", "hotknife_b", "cogcabri", "surano_convertable", "rapidgt", "stingerg_b", "coquette_b", "bullet", "carbon", "ninef2", "carboniz", "cheetah", "adder_b", "entityxf", "adder", "feltzer",
],
];
Now I generate the list like this using the 2 arrays above:
echo '<pre>';
foreach($vehicles as $category => $val) {
echo "vehicleSpawner " . $category . "[] = {\n";
foreach($val as $item) {
echo " { \"" . $item . "\", \"" . array_search($item, array_column($textures, $item)) . "\", \"\" },\n";
}
echo '}';
echo '<hr>';
}
This outputs something similar to:
{ "adder", "", "" },
The last 2 values are empty. What I want to achieve: Fill these out with the values from $textures array. In this case, I'm trying to fill it up like this:
// arg 1: name from $vehicles
// arg 2: key from $textures
// arg 3: val from $textures
{ "adder", "lgm_default", "adder" },
Currently my array_search($item, array_column($textures, $item)) method doesn't seem to work. How would I go and get this working? Help is appreciated, thanks all!
array_column($textures, $item) will search in array $textures key named $item, but there is no key with that name so it returns false, what you need to do is loop on $textures array and search if value $item exists:
foreach($val as $item) {
foreach($textures as $k => $v) {
//this will return array index or false if not exists
$pos = array_search($item, $v);
if ( $pos !== false )
echo " { \"" . $item . "\", \"" . $k . "\", \"".$v[$pos]."\" },\n";
}
}
If you want to see multiple matches within a given pair of subarrays, array_intersect() will compare both subarrays once and iterate the results. This is more efficient than running fresh array_search() calls for each element of one of the subarrays.
Code: (Demo)
foreach($vehicles as $category => $v_vals) {
echo "vehicleSpawner " . $category . "[] = {\n";
foreach($textures as $k => $t_vals) {
foreach (array_intersect($v_vals, $t_vals) as $match) {
echo " { \"$match\", \"$k\", \"$match\" },\n";
}
}
echo "}\n";
}
Output:
vehicleSpawner vehicleSuper[] = {
{ "adder", "lgm_default", "adder" },
{ "bullet", "lgm_default", "bullet" },
}
vehicleSpawner vehicleSport[] = {
}
If this isn't the exact output format/structure that you desire, it can be tweaked to accommodate.

iterate through json_encode array in PHP

i'm having problem on how to iterate in the array in json_encode.
I do ajax POST, in where i have a looping code that do "array push" in jQuery, something like this:
$(this).closest('tr.header').nextUntil('.header').each(function(){
i++;
var forms="<form method='POST'>"+$(this).html()+'</form>';
data.push($(forms).serializeArray());
});
So when i pass this to my controller/ other page, i do this:
$dataList = json_encode($this->input->post("form"));
echo $dataList ;
And the output is:
[
[{"name":"category_1", "values":"packages"},
{"name":"PK_1", "values": "1"}
],
[{"name":"category_2", "value":"products"},
{"name":"PK_2", "value": "3"}
]
]
I have tried to do :
foreach ($dataList as $data) {
echo $data . "\n";
}
But only give me error on foreach.
Thanks in advance.
Use json_decode()function to get your data as an array then foreach your data.
$a = '[
[{"name":"category_1", "values":"packages"},
{"name":"PK_1", "values": "1"}
],
[{"name":"category_2", "value":"products"},
{"name":"PK_2", "value": "3"}
]
]';
echo '<pre>';
$res = json_decode($a, true);
$newArr = [];
foreach($res as $data => $val)
{
foreach($val as $key2 => $val2)
{
$newArr[] = $val2;
}
}
foreach($newArr as $key => $val)
{
echo 'Name = ' . $val['name'] . ' Values = ' . $val['value'] . '<br/>';
}
Just decode the string and loop through the created array.
<?php
$a = '[
[{"name":"category_1", "values":"packages"},
{"name":"PK_1", "values": "1"}
],
[{"name":"category_2", "value":"products"},
{"name":"PK_2", "value": "3"}
]
]';
echo '<pre>';
$res = json_decode($a, true);
$newArr = array();
foreach($res as $data => $val)
{
foreach($val as $k=>$value){
$value=array_values($value);
echo 'Name => ' . $value[0] . ' Value => ' . $value[1] . '<br/>';
}
}
?>
for array output you need to decode it with json_decode()
here is sample code.
$encode_data = '[[{"name":"category_1", "values":"packages"},{"name":"PK_1", "values": "1"}],[{"name":"category_2", "value":"products"},{"name":"PK_2", "value": "3"}]]';
$dataAr = json_decode($encode_data , true);
foreach($dataAr as $data)
{
foreach($data as $value){
$value=array_values($value);
echo 'name => ' .$value[0] . ' value => ' .$value[1];
echo "<br>";
}
}

How to loop over and access various elements in an array that is both multidimentional and associative? PHP, either JSON or XML

I'm retrieving bibliographic data via an API (zotero.org), and it is similar to the sample at the bottom (just way more convoluted - sample is typed).
I want to retrieve one or more records and display certain values on the page. For example, I would like to loop through each top level record and print the data in a nicely formated citation. Ignoring the proper bib styles for the moment, let's say I want to just print out the following for each record returned:
author1 name, author2 name, article title, publication title, key
This doesn't match the code, because I've clearly been referencing the key value pairs incorrectly and will just make a mess of it.
The following is laid out like the data if I request JSON format, though I can request XML data instead. I'm not picky; I've tried using each with no luck.
[
{
"key": "123456",
"state": 100,
"data": {
"articleTitle": "Wombat coprogenetics: enumerating a common wombat population by microsatellite analysis of faecal DNA",
"authors": [
{
"firstName": "Sam C.",
"lastName": "Smith"
},
{
"firstName": "Maxine P.",
"lastName": "Jones"
}
],
"pubTitle": "Australian Journal of Zoology",
"tags": [
{
"tag": "scary"
},
{
"tag": "secret rulers of the world"
}
]
}
},
{
"key": "001122",
"state": 100,
"data": {
"articleTitle": "WOMBAT and WOMBAT-PK: Bioactivity Databases for Lead and Drug Discovery",
"authors": [
{
"firstName": "Marius",
"lastName": "Damstra"
}
],
"pubTitle": "Chemical Biology: From Small Molecules to Systems Biology",
"tags": [
{
"tag": "Wrong Wombat"
}
]
}
}
]
If there is a mistake in brackets, commas, etc. it is just a typo in my example and not the cause of my issue.
decode your json as array and iterate it as any array as flowing:
$json_decoded= json_decode($json,true);
$tab="\t";
foreach ($json_decoded as $key => $val) {
echo "Article ".$val["key"]."\n" ;
echo $tab."Authors :\n";
foreach ($val["data"]["authors"] as $key => $author){
echo $tab.$tab. ($key+1) ." - ".$author["firstName"]. " ".$author["lastName"]."\n";
}
echo $tab."Article Title: ".$val["data"]["articleTitle"] ."\n";
echo $tab."Publication Title: ".$val["data"]["pubTitle"] ."\n";
echo $tab."Key: ".$val["key"]."\n";
}
run on codepad
and you can use the same method for xml as flowing:
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$json_decoded = json_decode($json,TRUE);
//the rest is same
for xml you can use the SimpleXml's functions
or DOMDocument class
Tip
to know the structure of your data that api return to you after it converted to array use var_dump($your_decoded_json) in debuging
Something like this might be a good start for you:
$output = [];
// Loop through each entry
foreach ($data as $row) {
// Get the "data" block
$entry = $row['data'];
// Start your temporary array
$each = [
'article title' => $entry['articleTitle'],
'publication title' => $entry['pubTitle'],
'key' => $row['key']
];
// Get each author's name
foreach ($entry['authors'] as $i => $author) {
$each['author' . ++$i . ' name'] = $author['firstName'] . ' ' . $author['lastName'];
}
// Append it to your output array
$output[] = $each;
}
print_r($output);
Example: https://eval.in/369313
Have you tried to use array_map ?
That would be something like:
$entries = json_decode($json, true);
print_r(array_map(function ($entry) {
return implode(', ', array_map(function ($author) {
return $author['firstName'];
}, $entry['data']['authors'])) . ', ' . $entry['data']['articleTitle'] . ', ' . $entry['key'];
}, $entries));

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

How foreach array of object that actually field of another object?

I have such data structure of object:
"site":"http://mercurygold.com.ua/",
"shops":[
{
"id":"1",
"shopLogo":"mercuryGoldShop1",
"address":"test test test"
},
{
"id":"2",
"shopLogo":"mercuryGoldShop2",
"address":"text text text"
}
]
How can I foreach all 'shops' objects without addressing fields by names?
You can access it with 2 foreach loops. Assuming "shops" is in variable $var, you can access it like this:
foreach($var['shops'] as $shop)
{
foreach($shop as $key=>$val)
{
echo $key . ": " . $val . "\n";
}
}
Note: If the variable is JSON you will have to do $var = json_decode($var); first.
I pretty sure you it's a JSON format, to get elements shops you need to do this :
<?php
$var = '
{
"site":"http://mercurygold.com.ua/",
"shops":[
{
"id":"1",
"shopLogo":"mercuryGoldShop1",
"address":"test test test"
},
{
"id":"2",
"shopLogo":"mercuryGoldShop2",
"address":"text text text"
}
]
}';
$var = json_decode($var);
foreach($var->shops as $shop)
{
foreach($shop as $key=>$val)
{
echo $key . ": " . $val . "\n";
}
echo '<br>';
}
OUTPUT:
id: 1 shopLogo: mercuryGoldShop1 address: test test test
id: 2 shopLogo: mercuryGoldShop2 address: text text text

Categories