Change structure of array to create JSON - php
I would like to change structure of my array to produce slightly different JSON file. I tried putting 'category' into extra array but it doesn't work.
In JSON 'category' should be in aditional []:
"categories": [{
"category": [{
"label": "N.12\/02"
}, {
"label": "Pn.13\/02"
}, {
"label": "Wt.14\/02"
}, {
"label": "\u015ar.15\/02"
}, {
"label": "Cz.16\/02"
}, {
"label": "Pt.17\/02"
}, {
"label": "So.18\/02"
}]
}],
instead of:
"categories": {
"category": [{
"label": "N.12\/02"
}, {
"label": "Pn.13\/02"
}, {
"label": "Wt.14\/02"
}, {
"label": "\u015ar.15\/02"
}, {
"label": "Cz.16\/02"
}, {
"label": "Pt.17\/02"
}, {
"label": "So.18\/02"
}]
},
I am using this code to create array and than JSON:
$arrData = array(
"chart" => array(
"caption" => "Number of visitors last week",
"subCaption" => "Bakersfield Central vs Los Angeles Topanga",
"captionFontSize" => "14",
"subcaptionFontSize" => "14",
"subcaptionFontBold" => "0",
"paletteColors" => "#0075c2,#1aaf5d,#FF5733,#33B5FF",
"bgcolor" => "#ffffff",
"showBorder" => "0",
"showShadow" => "0",
"showCanvasBorder" => "0",
"usePlotGradientColor" => "0",
"legendBorderAlpha" => "0",
"legendShadow" => "0",
"showAxisLines" => "0",
"showAlternateHGridColor" => "0",
"divlineThickness" => "1",
"divLineDashed" => "1",
"divLineDashLen" => "1",
"xAxisName" => "Day",
"showValues" => "0"
)
);
$actualCategory = array( $rowData[0][1], $rowData[0][2], $rowData[0][3], $rowData[0][4], $rowData[0][5], $rowData[0][6], $rowData[0][7]);
$a = array(
array( $rowData[2][1], $rowData[2][2], $rowData[2][3], $rowData[2][4], $rowData[2][5], $rowData[2][6], $rowData[2][7]),
array( $rowData[5][1], $rowData[5][2], $rowData[5][3], $rowData[5][4], $rowData[5][5], $rowData[5][6], $rowData[5][7]),
array( $rowData[8][1], $rowData[8][2], $rowData[8][3], $rowData[8][4], $rowData[8][5], $rowData[8][6], $rowData[8][7]),
array( $rowData[11][1], $rowData[11][2], $rowData[11][3], $rowData[11][4], $rowData[11][5], $rowData[11][6], $rowData[11][7])
);
$arrData['categories'] = array( 'category' => array());
foreach ($actualCategory as $value) {
array_push($arrData['categories']['category'],
array(
'label' => $value
)
);
}
$arrData['dataset'] = array();
$q = 1;
for($z = 0;$z <= 3; $z++){
$x[$z] = array('seriesname' => $rowData[$q][0], 'data' => array());
foreach ($a[$z] as $value) {
array_push($x[$z]['data'],
array(
'value' => $value
)
);
}
$q = $q + 3;
}
$arrData['dataset'] = $x;
$jsonEncodedData = json_encode($arrData);
At this moment I have this output:
{"chart":{"caption":"Number of visitors last week","subCaption":"Bakersfield Central vs Los Angeles Topanga","captionFontSize":"14","subcaptionFontSize":"14","subcaptionFontBold":"0","paletteColors":"#0075c2,#1aaf5d,#FF5733,#33B5FF","bgcolor":"#ffffff","showBorder":"0","showShadow":"0","showCanvasBorder":"0","usePlotGradientColor":"0","legendBorderAlpha":"0","legendShadow":"0","showAxisLines":"0","showAlternateHGridColor":"0","divlineThickness":"1","divLineDashed":"1","divLineDashLen":"1","xAxisName":"Day","showValues":"0"},"categories":{"category":[{"label":"N.12\/02"},{"label":"Pn.13\/02"},{"label":"Wt.14\/02"},{"label":"\u015ar.15\/02"},{"label":"Cz.16\/02"},{"label":"Pt.17\/02"},{"label":"So.18\/02"}]},"dataset":[{"seriesname":"IRDN","data":[{"value":"142.59"},{"value":"174.88"},{"value":"176.97"},{"value":"182.48"},{"value":"160.15"},{"value":"160.72"},{"value":"165.47"}]},{"seriesname":"SIRDN","data":[{"value":"148.81"},{"value":"197.29"},{"value":"202.27"},{"value":"211.93"},{"value":"177.87"},{"value":"179.37"},{"value":"177.69"}]},{"seriesname":"IRDN24","data":[{"value":"140.31"},{"value":"174.50"},{"value":"180.38"},{"value":"187.70"},{"value":"161.91"},{"value":"161.62"},{"value":"160.98"}]},{"seriesname":"IRDN 8.22","data":[{"value":"147.33"},{"value":"197.02"},{"value":"202.21"},{"value":"211.28"},{"value":"178.11"},{"value":"179.32"},{"value":"176.31"}]}]}
JSON file I need:
{"chart":{"caption":"Number of visitors last week","subCaption":"Bakersfield Central vs Los Angeles Topanga","captionFontSize":"14","subcaptionFontSize":"14","subcaptionFontBold":"0","paletteColors":"#0075c2,#1aaf5d,#FF5733,#33B5FF","bgcolor":"#ffffff","showBorder":"0","showShadow":"0","showCanvasBorder":"0","usePlotGradientColor":"0","legendBorderAlpha":"0","legendShadow":"0","showAxisLines":"0","showAlternateHGridColor":"0","divlineThickness":"1","divLineDashed":"1","divLineDashLen":"1","xAxisName":"Day","showValues":"0"},"categories":[{"category":[{"label":"N.12\/02"},{"label":"Pn.13\/02"},{"label":"Wt.14\/02"},{"label":"\u015ar.15\/02"},{"label":"Cz.16\/02"},{"label":"Pt.17\/02"},{"label":"So.18\/02"}]}],"dataset":[{"seriesname":"IRDN","data":[{"value":"142.59"},{"value":"174.88"},{"value":"176.97"},{"value":"182.48"},{"value":"160.15"},{"value":"160.72"},{"value":"165.47"}]},{"seriesname":"SIRDN","data":[{"value":"148.81"},{"value":"197.29"},{"value":"202.27"},{"value":"211.93"},{"value":"177.87"},{"value":"179.37"},{"value":"177.69"}]},{"seriesname":"IRDN24","data":[{"value":"140.31"},{"value":"174.50"},{"value":"180.38"},{"value":"187.70"},{"value":"161.91"},{"value":"161.62"},{"value":"160.98"}]},{"seriesname":"IRDN 8.22","data":[{"value":"147.33"},{"value":"197.02"},{"value":"202.21"},{"value":"211.28"},{"value":"178.11"},{"value":"179.32"},{"value":"176.31"}]}]}
Dump of my array:
array(3) { ["chart"]=> array(20) { ["caption"]=> string(28) "Number of visitors last week" ["subCaption"]=> string(42) "Bakersfield Central vs Los Angeles Topanga" ["captionFontSize"]=> string(2) "14" ["subcaptionFontSize"]=> string(2) "14" ["subcaptionFontBold"]=> string(1) "0" ["paletteColors"]=> string(31) "#0075c2,#1aaf5d,#FF5733,#33B5FF" ["bgcolor"]=> string(7) "#ffffff" ["showBorder"]=> string(1) "0" ["showShadow"]=> string(1) "0" ["showCanvasBorder"]=> string(1) "0" ["usePlotGradientColor"]=> string(1) "0" ["legendBorderAlpha"]=> string(1) "0" ["legendShadow"]=> string(1) "0" ["showAxisLines"]=> string(1) "0" ["showAlternateHGridColor"]=> string(1) "0" ["divlineThickness"]=> string(1) "1" ["divLineDashed"]=> string(1) "1" ["divLineDashLen"]=> string(1) "1" ["xAxisName"]=> string(3) "Day" ["showValues"]=> string(1) "0" } ["categories"]=> array(1) { ["category"]=> array(7) { [0]=> array(1) { ["label"]=> string(80) " N. 12/02 " } [1]=> array(1) { ["label"]=> string(81) " Pn. 13/02 " } [2]=> array(1) { ["label"]=> string(81) " Wt. 14/02 " } [3]=> array(1) { ["label"]=> string(82) " Śr. 15/02 " } [4]=> array(1) { ["label"]=> string(81) " Cz. 16/02 " } [5]=> array(1) { ["label"]=> string(81) " Pt. 17/02 " } [6]=> array(1) { ["label"]=> string(81) " So. 18/02 " } } } ["dataset"]=> array(4) { [0]=> array(2) { ["seriesname"]=> string(34) " IRDN " ["data"]=> array(7) { [0]=> array(1) { ["value"]=> string(43) " 142.59 " } [1]=> array(1) { ["value"]=> string(43) " 174.88 " } [2]=> array(1) { ["value"]=> string(43) " 176.97 " } [3]=> array(1) { ["value"]=> string(43) " 182.48 " } [4]=> array(1) { ["value"]=> string(43) " 160.15 " } [5]=> array(1) { ["value"]=> string(43) " 160.72 " } [6]=> array(1) { ["value"]=> string(43) " 165.47 " } } } [1]=> array(2) { ["seriesname"]=> string(80) " SIRDN " ["data"]=> array(7) { [0]=> array(1) { ["value"]=> string(61) " 148.81 " } [1]=> array(1) { ["value"]=> string(61) " 197.29 " } [2]=> array(1) { ["value"]=> string(61) " 202.27 " } [3]=> array(1) { ["value"]=> string(61) " 211.93 " } [4]=> array(1) { ["value"]=> string(61) " 177.87 " } [5]=> array(1) { ["value"]=> string(61) " 179.37 " } [6]=> array(1) { ["value"]=> string(61) " 177.69 " } } } [2]=> array(2) { ["seriesname"]=> string(74) " IRDN24 " ["data"]=> array(7) { [0]=> array(1) { ["value"]=> string(60) " 140.31 " } [1]=> array(1) { ["value"]=> string(60) " 174.50 " } [2]=> array(1) { ["value"]=> string(60) " 180.38 " } [3]=> array(1) { ["value"]=> string(60) " 187.70 " } [4]=> array(1) { ["value"]=> string(60) " 161.91 " } [5]=> array(1) { ["value"]=> string(60) " 161.62 " } [6]=> array(1) { ["value"]=> string(60) " 160.98 " } } } [3]=> array(2) { ["seriesname"]=> string(112) " IRDN 8.22 " ["data"]=> array(7) { [0]=> array(1) { ["value"]=> string(69) " 147.33 " } [1]=> array(1) { ["value"]=> string(69) " 197.02 " } [2]=> array(1) { ["value"]=> string(69) " 202.21 " } [3]=> array(1) { ["value"]=> string(69) " 211.28 " } [4]=> array(1) { ["value"]=> string(69) " 178.11 " } [5]=> array(1) { ["value"]=> string(69) " 179.32 " } [6]=> array(1) { ["value"]=> string(69) " 176.31 " } } } } }
My question is how to change my code do this?
You should use
$arrData['categories'] = array( array ('category' => array()));
instead of
$arrData['categories'] = array( 'category' => array());
It will works as you want to.
Related
PHP Convert multidimensional array key to be array multidimensional value
I have problem formatting array to become fancytree format, below array output from db: array(44) { [0]=> array(3) { ["id"]=> string(2) "35" ["title"]=> string(28) "ROOT1" ["path"]=> string(28) "ROOT1" } [1]=> array(3) { ["id"]=> string(2) "36" ["title"]=> string(27) "SUB_A" ["path"]=> string(56) "ROOT1>SUB_A" } [2]=> array(3) { ["id"]=> string(2) "39" ["title"]=> string(12) "SUB_A_1" ["path"]=> string(69) "ROOT1>SUB_A>SUB_A_1" } [3]=> array(3) { ["id"]=> string(2) "37" ["title"]=> string(28) "SUB_A_2" ["path"]=> string(85) "ROOT1>SUB_A>SUB_A_2" } [4]=> array(3) { ["id"]=> string(2) "40" ["title"]=> string(30) "SUB_A_3" ["path"]=> string(87) "ROOT1>SUB_A>SUB_A_3" } [5]=> array(3) { ["id"]=> string(2) "43" ["title"]=> string(19) "SUB_A_4" ["path"]=> string(76) "ROOT1>SUB_A>SUB_A_4" } [6]=> array(3) { ["id"]=> string(2) "41" ["title"]=> string(12) "SUB_A_5" ["path"]=> string(69) "ROOT1>SUB_A>SUB_A_5" } [7]=> array(3) { ["id"]=> string(1) "1" ["title"]=> string(20) "ROOT2" ["path"]=> string(20) "ROOT2" } [8]=> array(3) { ["id"]=> string(2) "30" ["title"]=> string(37) "ROOT3" ["path"]=> string(37) "ROOT3" } [9]=> array(3) { ["id"]=> string(2) "34" ["title"]=> string(21) "SUB_B" ["path"]=> string(59) "ROOT3>SUB_B" } [10]=> array(3) { ["id"]=> string(2) "31" ["title"]=> string(15) "SUB_C" ["path"]=> string(53) "ROOT3>SUB_C" } I want to format values of path become structured array, here is what I try: function format(array $data) : array { $single = []; // format to single data foreach ($data as $value) { $single[] = $value['path']; } $result = []; foreach ($single as $path) { $parts = explode('>', $path); $section = &$result; $sectionName = ''; foreach ($parts as $part) { $sectionName = $part; if (array_key_exists($sectionName, $section) === FALSE) { $section[$sectionName] = []; } $section = &$section[$sectionName]; } } return $result; } result: array(3) { ["ROOT1"]=> array(1) { ["SUB_A"]=> array(5) { ["SUB_A_1"]=> array(0) { } ["SUB_A_2"]=> array(0) { } ["SUB_A_3"]=> array(0) { } ["SUB_A_4"]=> array(0) { } ["SUB_A_5"]=> array(0) { } } } ["ROOT2"]=> array(0) { } ["ROOT3"]=> array(2) { ["SUB_B"]=> array(0) { } ["SUB_C"]=> array(0) { } } i need to include values of id and title to each path as expected result: array(3) { [0]=> array(3) { ["title"]=> string(5) "ROOT1" ["id"]=> int(35) ["children"]=> array(1) { [0]=> array(3) { ["title"]=> string(5) "SUB_A" ["id"]=> int(36) ["children"]=> array(5) { [0]=> array(2) { ["title"]=> string(7) "SUB_A_1" ["id"]=> int(39) } [1]=> array(2) { ["title"]=> string(7) "SUB_A_2" ["id"]=> int(37) } [2]=> array(2) { ["title"]=> string(7) "SUB_A_3" ["id"]=> int(40) } [3]=> array(2) { ["title"]=> string(7) "SUB_A_4" ["id"]=> int(43) } [4]=> array(2) { ["title"]=> string(7) "SUB_A_5" ["id"]=> int(41) } } } } } [1]=> array(2) { ["title"]=> string(5) "ROOT2" ["id"]=> int(1) } [2]=> array(3) { ["title"]=> string(5) "ROOT3" ["id"]=> int(30) ["children"]=> array(2) { [0]=> array(2) { ["title"]=> string(5) "SUB_B" ["id"]=> int(34) } [1]=> array(2) { ["title"]=> string(5) "SUB_C" ["id"]=> int(31) } } } } I would be grateful for any help you are able to provide.
Here's how I would do it. Test I used arrow functions to reduce the amount of lines and there are inline comments to explain what I did. <?php $data = [["id"=> "35", "title"=> "ROOT1", "path"=> "ROOT1"], ["id"=> "36", "title"=> "SUB_A", "path"=> "ROOT1>SUB_A"], ["id"=> "37", "title"=> "SUB_A_1", "path"=> "ROOT1>SUB_A>SUB_A_1"], ["id"=> "38", "title"=> "SUB_A_2", "path"=> "ROOT1>SUB_A>SUB_A_2"], ["id"=> "39", "title"=> "SUB_A_3", "path"=> "ROOT1>SUB_A>SUB_A_3"], ["id"=> "40", "title"=> "SUB_A_4", "path"=> "ROOT1>SUB_A>SUB_A_4"], ["id"=> "41", "title"=> "SUB_A_5", "path"=> "ROOT1>SUB_A>SUB_A_5"], ["id"=> "1", "title"=> "ROOT2", "path"=> "ROOT2"], ["id"=> "30", "title"=> "ROOT3", "path"=> "ROOT3"], ["id"=> "34", "title"=> "SUB_B", "path"=> "ROOT3>SUB_B"], ["id"=> "31", "title"=> "SUB_C", "path"=> "ROOT3>SUB_C"]]; // The path is defaulted to an empty string, so the regex would return the highest level elements only because they don't have any `>` function get_children($data, $path = '') { $results = array_values(array_filter($data, fn($item) => preg_match("/^{$path}[^>]+$/", $item['path']))); // This regex, uses the passed path (e.g ROOT1) and searches for elements with anything but another `>`, because `>` signifies an inner directory. // So this would return elements with a path like `ROOT1>SUB_A, ROOT1>SUB_B` but not `ROOT1>SUB_A>SUB_A_1` foreach($results as $i => $result) { // then I iterate through the result to get the element's children $children = array_values(get_children($data, "{$result['path']}>")); if (count($children)) $results[$i]['children'] = $children; unset($results[$i]['path']); // Removing the path key from the array } return $results; } $format = fn($data) => get_children($data); print_r($format($data));
Split array with equal indices
I have a result array which is formatted like the following: array(6) { [0]=> array(3) { ["company"]=> string(1) "A" ["uf_prop"]=> string(2) "GO" ["qtd_prop_uf"]=> string(3) "612" } [1]=> array(3) { ["company"]=> string(1) "A" ["uf_prop"]=> string(2) "MG" ["qtd_prop_uf"]=> string(1) "1" } [2]=> array(3) { ["company"]=> string(1) "A" ["uf_prop"]=> string(2) "MS" ["qtd_prop_uf"]=> string(2) "11" } [3]=> array(3) { ["company"]=> string(1) "A" ["uf_prop"]=> string(2) "MT" ["qtd_prop_uf"]=> string(1) "4" } [4]=> array(3) { ["company"]=> string(1) "A" ["uf_prop"]=> string(2) "PA" ["qtd_prop_uf"]=> string(4) "2213" } [5]=> array(3) { ["company"]=> string(1) "B" ["uf_prop"]=> string(2) "PA" ["qtd_prop_uf"]=> string(1) "6" } } I want to split and organize this array like the following example if it is possible: company: A uf_prop: GO, MG, MS, MT, PA qtd_pro_uf: 612, 1, 11, 4, 2213 company: B uf_prop: PA qtd_pro_uf: 6 I wish I could divide by 2 or more if there are more companies and then show the states and the amount of a priori stores.
I feel the array structure is like php, so here is php solution. $result = []; foreach ($arr as $key => $value) { $result[$value['company']]['uf_prop'][] = $value['uf_prop']; $result[$value['company']]['qtd_pro_uf'][] = $value['qtd_pro_uf']; } foreach ($result as $key => $value) { echo "company: " . $key . "<br/>"; echo "uf_prop: " . implode(",", $value['uf_prop']) . "<br/>"; echo "qtd_pro_uf: " . implode(",", $value['qtd_pro_uf']) . "<br/>"; }
Fatal error: Cannot use string offset as an array - What the right way to compare array value
I call to array and try to compare the values, is there something wrong in my syntax? foreach ($xml_record_ray['inf']['rec'] as $key_item => $item) { $field = "100"; if ($item["#attributes"]["tag"] == $field) { } } This is my array: array(1) { ["inf"]=> array(9) { ["hid"]=> string(13) "4754745675467" ["created_by"]=> string(6) "import" ["created_date"]=> string(11) "2017-01-01Z" ["last_modified_by"]=> string(13) "Update Record" ["last_modified_date"]=> string(11) "2018-01-2Z" ["originating_system"]=> string(3) "rrr" ["orid"]=> string(15) "1234565432167854" ["supp"]=> string(5) "false" ["rec"]=> array(3) { ["lead"]=> string(3) "500" ["field"]=> array(2) { [0]=> array(2) { ["#value"]=> string(5) "22333" ["#attributes"]=> array(1) { ["tag"]=> string(3) "001" } } [1]=> array(2) { ["#value"]=> string(3) "110" ["#attributes"]=> array(1) { ["tag"]=> string(3) "001" } } } ["dfield"]=> array(2) { [0]=> array(2) { ["subfield"]=> array(2) { ["#value"]=> string(2) "92" ["#attributes"]=> array(1) { ["cod"]=> string(1) "a" } } ["#attributes"]=> array(3) { ["ind1"]=> string(1) " " ["ind2"]=> string(1) " " ["tag"]=> string(3) "101" } } [1]=> array(2) { ["subfield"]=> array(3) { [0]=> array(2) { ["#value"]=> string(4) "ntft" ["#attributes"]=> array(1) { ["cod"]=> string(1) "b" } } [1]=> array(2) { ["#value"]=> string(5) "nthgfr" ["#attributes"]=> array(1) { ["cod"]=> string(1) "c" } } [2]=> array(2) { ["#value"]=> string(5) "test2" ["#attributes"]=> array(1) { ["cod"]=> string(1) "z" } } } ["#attributes"]=> array(3) { ["ind1"]=> string(1) "1" ["ind2"]=> string(1) " " ["tag"]=> string(3) "100" } } } } } } I compare `tag = 100` to a variable with value 100: `if ($item["#attributes"]["tag"] == $field)` This array I received after changes that used from last discussion from this post: array(1) { ["inf"]=> array(9) { ["hid"]=> string(13) "4754745675467" ["created_by"]=> string(6) "import" ["created_date"]=> string(11) "2017-01-01Z" ["last_modified_by"]=> string(13) "Update Record" ["last_modified_date"]=> string(11) "2018-01-2Z" ["originating_system"]=> string(3) "rrr" ["orid"]=> string(15) "1234565432167854" ["supp"]=> string(5) "false" ["rec"]=> array(3) { ["lead"]=> string(3) "500" ["field"]=> array(2) { [0]=> array(2) { ["#value"]=> string(5) "22333" ["#attributes"]=> array(1) { ["tag"]=> string(3) "001" } } [1]=> array(2) { ["#value"]=> string(3) "110" ["#attributes"]=> array(1) { ["tag"]=> string(3) "001" } } } ["dfield"]=> array(3) { [0]=> array(2) { ["subfield"]=> array(2) { ["#value"]=> string(2) "92" ["#attributes"]=> array(1) { ["cod"]=> string(1) "a" } } ["#attributes"]=> array(3) { ["ind1"]=> string(1) " " ["ind2"]=> string(1) " " ["tag"]=> string(3) "101" } } [1]=> array(2) { ["subfield"]=> array(3) { [0]=> array(2) { ["#value"]=> string(4) "ntft" ["#attributes"]=> array(1) { ["code"]=> string(1) "b" } } [1]=> array(2) { ["#value"]=> string(5) "nthgfr" ["#attributes"]=> array(1) { ["code"]=> string(1) "c" } } [2]=> array(2) { ["#value"]=> string(4) "test" ["#attributes"]=> array(1) { ["cod"]=> string(1) "z" } } } ["#attributes"]=> array(3) { ["ind1"]=> string(1) "1" ["ind2"]=> string(1) " " ["tag"]=> string(3) "100" } } ["subfield"]=> array(1) { [2]=> array(1) { ["#value"]=> string(12) "26A 1 2 test" } } } } } }
You're using ["#attributes"] but $item is not a "standard" array. It seems to be a SimpleXMLElement object. Try to use the following code : foreach ($xml_record_ray['inf']['rec'] as $key_item => $item) { $field = "100"; if ((string)$item["tag"] == $field) { var_dump("Equals") ; } } edit $field = "100"; foreach ($xml_record_ray['inf']['rec'] as $key_item => $item) { var_dump($key_item) ; if (is_array($item)) { foreach ($item as $key_element => $element) { var_dump($key_element) ; if (!isset($element["#attributes"])) { echo("no attribute"); continue ; } if (!isset($element["#attributes"]['tag'])) { echo("no tag"); continue; } if ($element["#attributes"]["tag"] == $field) { var_dump("match") ; } } } else{ echo "item is not an array" ; } }
Print data retrieved in JSON on a PHP
I'm trying to print a table with the list of Monitoring Groups from data retrieved from a REST API. The results come back in JSON. Below is the JSON data: { "code": 0, "message": "success", "data": [ { "group_id": "169839000000116001", "display_name": "MTI Servers", "description": "", "monitors": [ ] }, { "group_id": "169839000000180001", "display_name": "PRB Servers", "description": "", "monitors": [ "169839000000179003", "169839000000176013", "169839000000175003", "169839000000176007" ] }, { "group_id": "169839000000046270", "display_name": "DB Servers", "description": "", "monitors": [ "169839000000051011", "169839000000047023", "169839000000078001" ] }, { "group_id": "169839000000025200", "display_name": "EXT Apps", "description": "External Monitoring of Applications", "monitors": [ "169839000000025274", "169839000000025377", "169839000000025359", "169839000000025369", "169839000000025385", "169839000000025226" ] }, { "group_id": "169839000000025109", "display_name": "EXT Services", "description": "External monitoring of services.", "monitors": [ "169839000000046165", "169839000000025256", "169839000000025168", "169839000000025202", "169839000000025189", "169839000000025217", "169839000000025265" ] }, { "group_id": "169839000000046015", "display_name": "ZMB Servers", "description": "", "monitors": [ "169839000000050017", "169839000000050025", "169839000000049001", "169839000000050001", "169839000000053019", "169839000000051003", "169839000000050009" ] }, { "group_id": "169839000000046282", "display_name": "NWK Devices", "description": "", "monitors": [ "169839000000082009", "169839000000084077", "169839000000084001", "169839000000082229" ] }, { "group_id": "169839000000046013", "display_name": "VBR Servers", "description": "", "monitors": [ "169839000000047007" ] }, { "group_id": "169839000000054197", "display_name": "LNX Servers", "description": "", "monitors": [ "169839000000060483" ] }, { "group_id": "169839000000046020", "display_name": "VSP Servers", "description": "", "monitors": [ "169839000000060177", "169839000000060170", "169839000000060088", "169839000000060095", "169839000000060102", "169839000000060109", "169839000000054102" ] }, { "group_id": "169839000000046058", "display_name": "WND Servers", "description": "", "monitors": [ "169839000000066001", "169839000000063119" ] }, { "group_id": "169839000000128001", "display_name": "TPT Servers", "description": "", "monitors": [ "169839000000143041", "169839000000148017", "169839000000127035", "169839000000123003", "169839000000126011", "169839000000122011", "169839000000129001", "169839000000158028" ] } ] } I want to print the Group ID, Name, Description and the list of monitor IDs that belong to the group. I'm using json_decode but I cant seem to read the correct variables from the array. Here's the code I have so far: `<?php /** * Connect to the Site API and extract the list of monitor groups */ // URL to fetch $url = "https://www.mymonitorsite.com/api/monitor_groups"; // Initialize cURL session $ch = curl_init($url); // Option to Return the Result, rather than just true/false curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Set Custom Headers $headers = array( 'Authorization: Authtoken 12345678901234567890123456789012', 'Content-Type: application/json;charset=UTF-8', 'Accept: application/json; version=2.0', ); // Option to set the custom headers curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // Perform the request, and save content to $result $mongrps_json = curl_exec($ch); // Close the cURL resource, and free up system resources! curl_close($ch); // Decode json data into a PHP Array $mongrps_array = json_decode($mongrps_json, true); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Monitor Group Test</title> </head> <body> <?php // List the first monitor group here (test) echo "Group ID = " . $mongrps_array->data[0]->group_id . "<br>"; echo "Group Name = " . $mongrps_array->data[0]->display_name . <br>"; ?> </body> </html> ` Here's a var_dump of the json_decode: array(3) { ["code"]=> int(0) ["message"]=> string(7) "success" ["data"]=> array(12) { [0]=> array(4) { ["group_id"]=> string(18) "169839000000116001" ["display_name"]=> string(11) "MTI Servers" ["description"]=> string(0) "" ["monitors"]=> array(0) { } } [1]=> array(4) { ["group_id"]=> string(18) "169839000000180001" ["display_name"]=> string(11) "PRB Servers" ["description"]=> string(0) "" ["monitors"]=> array(4) { [0]=> string(18) "169839000000179003" [1]=> string(18) "169839000000176013" [2]=> string(18) "169839000000175003" [3]=> string(18) "169839000000176007" } } [2]=> array(4) { ["group_id"]=> string(18) "169839000000046270" ["display_name"]=> string(10) "DB Servers" ["description"]=> string(0) "" ["monitors"]=> array(3) { [0]=> string(18) "169839000000051011" [1]=> string(18) "169839000000047023" [2]=> string(18) "169839000000078001" } } [3]=> array(4) { ["group_id"]=> string(18) "169839000000025200" ["display_name"]=> string(8) "EXT Apps" ["description"]=> string(35) "External Monitoring of Applications" ["monitors"]=> array(6) { [0]=> string(18) "169839000000025274" [1]=> string(18) "169839000000025377" [2]=> string(18) "169839000000025359" [3]=> string(18) "169839000000025369" [4]=> string(18) "169839000000025385" [5]=> string(18) "169839000000025226" } } [4]=> array(4) { ["group_id"]=> string(18) "169839000000025109" ["display_name"]=> string(12) "EXT Services" ["description"]=> string(31) "External monitoring of services" ["monitors"]=> array(7) { [0]=> string(18) "169839000000046165" [1]=> string(18) "169839000000025256" [2]=> string(18) "169839000000025168" [3]=> string(18) "169839000000025202" [4]=> string(18) "169839000000025189" [5]=> string(18) "169839000000025217" [6]=> string(18) "169839000000025265" } } [5]=> array(4) { ["group_id"]=> string(18) "169839000000046015" ["display_name"]=> string(11) "ZMB Servers" ["description"]=> string(0) "" ["monitors"]=> array(7) { [0]=> string(18) "169839000000050017" [1]=> string(18) "169839000000050025" [2]=> string(18) "169839000000049001" [3]=> string(18) "169839000000050001" [4]=> string(18) "169839000000053019" [5]=> string(18) "169839000000051003" [6]=> string(18) "169839000000050009" } } [6]=> array(4) { ["group_id"]=> string(18) "169839000000046282" ["display_name"]=> string(11) "NWK Devices" ["description"]=> string(0) "" ["monitors"]=> array(4) { [0]=> string(18) "169839000000082009" [1]=> string(18) "169839000000084077" [2]=> string(18) "169839000000084001" [3]=> string(18) "169839000000082229" } } [7]=> array(4) { ["group_id"]=> string(18) "169839000000046013" ["display_name"]=> string(11) "VBR Servers" ["description"]=> string(0) "" ["monitors"]=> array(1) { [0]=> string(18) "169839000000047007" } } [8]=> array(4) { ["group_id"]=> string(18) "169839000000054197" ["display_name"]=> string(11) "LNX Servers" ["description"]=> string(0) "" ["monitors"]=> array(1) { [0]=> string(18) "169839000000060483" } } [9]=> array(4) { ["group_id"]=> string(18) "169839000000046020" ["display_name"]=> string(11) "VSP Servers" ["description"]=> string(0) "" ["monitors"]=> array(7) { [0]=> string(18) "169839000000060177" [1]=> string(18) "169839000000060170" [2]=> string(18) "169839000000060088" [3]=> string(18) "169839000000060095" [4]=> string(18) "169839000000060102" [5]=> string(18) "169839000000060109" [6]=> string(18) "169839000000054102" } } [10]=> array(4) { ["group_id"]=> string(18) "169839000000046058" ["display_name"]=> string(11) "WND Servers" ["description"]=> string(0) "" ["monitors"]=> array(2) { [0]=> string(18) "169839000000066001" [1]=> string(18) "169839000000063119" } } [11]=> array(4) { ["group_id"]=> string(18) "169839000000128001" ["display_name"]=> string(11) "TPT Servers" ["description"]=> string(0) "" ["monitors"]=> array(8) { [0]=> string(18) "169839000000143041" [1]=> string(18) "169839000000148017" [2]=> string(18) "169839000000127035" [3]=> string(18) "169839000000123003" [4]=> string(18) "169839000000126011" [5]=> string(18) "169839000000122011" [6]=> string(18) "169839000000129001" [7]=> string(18) "169839000000158028" } } } }
Use foreach loop to display the following data: group_id display_name description and monitors(as a comma separated list) $mongrps_array = json_decode($mongrps_json, true); foreach($mongrps_array['data'] as $arr){ foreach($arr as $key => $value){ if($key == "monitors"){ echo $key . ": " . implode(", ", $value) . "<br />"; }else{ echo $key . ": " . $value . "<br />"; } } echo "<br />"; }
I Just tried, should not be any issue to get the data you are looking for. For example, to get the group_id of the first item in the array: echo $decodedJson->data[0]->group_id; Maybe you are trying to get the data as arrays? In this case, pass the parameter true to the json_decode function: $decodedJson = json_decode($originalJson, true); echo $decodedJson['data'][0]['group_id'];
Parsing JSON Url with an Array Response
I'm running this code in php: $jsonData = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=306%20Evarts%20St%20NE%20Washington,%20DC%2020002&key=<hidden>'); $data = json_decode($jsonData, true); var_dump($data); with the following result (reformatted to be readable): array(2) { ["results"] => array(1) { [0] => array(5) { ["address_components"] => array(7) { [0] => array(3) { ["long_name"] => string(3) "306" ["short_name"]=> string(3) "306" ["types"] => array(1) { [0]=> string(13) "street_number" } } [1] => array(3) { ["long_name"] => string(23) "Evarts Street Northeast" ["short_name"] => string(12) "Evarts St NE" ["types"] => array(1) { [0]=> string(5) "route" } } [2] => array(3) { ["long_name"] => string(20) "Northeast Washington" ["short_name"] => string(20) "Northeast Washington" ["types"] => array(2) { [0] => string(12) "neighborhood" [1] => string(9) "political" } } [3] => array(3) { ["long_name"] => string(10) "Washington" ["short_name"]=> string(4) "D.C." ["types"]=> array(2) { [0]=> string(8) "locality" [1]=> string(9) "political" } } [4]=> array(3) { ["long_name"]=> string(20) "District of Columbia" ["short_name"]=> string(2) "DC" ["types"]=> array(2) { [0]=> string(27) "administrative_area_level_1" [1]=> string(9) "political" } } [5]=> array(3) { ["long_name"]=> string(13) "United States" ["short_name"]=> string(2) "US" ["types"]=> array(2) { [0]=> string(7) "country" [1]=> string(9) "political" } } [6]=> array(3) { ["long_name"]=> string(5) "20002" ["short_name"]=> string(5) "20002" ["types"]=> array(1) { [0]=> string(11) "postal_code" } } } ["formatted_address"]=> string(54) "306 Evarts Street Northeast, Washington, DC 20002, USA" ["geometry"]=> array(3) { ["location"]=> array(2) { ["lat"]=> float(38.9248059) ["lng"]=> float(-77.001318) } ["location_type"]=> string(7) "ROOFTOP" ["viewport"]=> array(2) { ["northeast"]=> array(2) { ["lat"]=> float(38.926154880291) ["lng"]=> float(-76.999969019709) } ["southwest"]=> array(2) { ["lat"]=> float(38.923456919708) ["lng"]=> float(-77.002666980292) } } } ["place_id"]=> string(27) "ChIJvysMWvjHt4kRjif4nyaEb7U" ["types"]=> array(1) { [0]=> string(14) "street_address" } } } ["status"]=> string(2) "OK" } How can I echo various values in the results for example long_name of address components?
you can use nested foreach to loop array ref : http://php.net/manual/en/control-structures.foreach.php foreach($data['results'] as $result){ foreach ($result['address_components'] as $value) { echo $value['long_name'] . '<br>'; } }
You can access response data as shown below: $jsonData = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=306%20Evarts%20St%20NE%20Washington,%20DC%2020002&key=API_KEY'); $data = json_decode($jsonData, true); if($data['status'] == 'OK'){ $latitude = $data['results'][0]['geometry']['location']['lat']; $longitude = $data['results'][0]['geometry']['location']['lng']; $formatted_address = $data['results'][0]['formatted_address']; }