I have data in Json format which i have decoded into a php array which when printed produces the following (just a snippet of the information).
Array (
[Title] => Array([Heading] => Company Name [Info] =>)
[SubTitle] => Array([Heading] => Welcome to Company Name[Info] =>information on the company)
)
my question is how do I loop through this information and print the title and then print the value.
I have tried the following which prints all the data at one time
foreach($data['SubTitle'] as $key => $value){
echo $value;
}
And then i tried this just to print the info section which i thought might work but instead throws an illegal string offset error
foreach($data['SubTitle'] as $key => $v){
echo $v['Info'];
}
I can get the information from the Title array as it is straight forward as it only has data value in the heading. However i would like the output from the Subtitle array to print the heading and info like below:
Welcome to Company Name
Information on the company
I thought this would be straight forward but it is turning out much more difficult than expected and has taken up a lot of time so any help would be greatly appreciated.
So I am going to assume you have a JSON string that looks like this:
$json = '{"Title":{"Heading": "Company Name", "Info": null}, "SubTitle": {"Heading": "Welcome to Company Name", "Info": "information on the company"}}';
visualised, looks something like this:
So, if you've decoded this json into an associative array:
$result = json_decode($json, true);
Then, in order to access the data, you don't need to "loop" over it; all you need to do is:
echo $result['Title']['Heading']; // will print 'Company Name'
echo $result['Title']['Info']; // will print nothing, as it is empty
echo $result['SubTitle']['Heading']; // will print 'Welcome to Company Name'
echo $result['SubTitle']['Info']; // will print 'information on the company'
Hope this helps. This is basic php, please look into the following reading materials:
https://www.php.net/manual/en/function.json-decode.php
https://www.w3schools.com/php/php_arrays.asp
Change your code, from this:
foreach($data['SubTitle'] as $key => $v){
echo $v['Info'];
}
To this:
foreach($data['SubTitle'] as $v){
echo $v . "<br/>"; // the <br/> makes a new line
}
Output will be:
Welcome to Company Name
Information on the company
$v is no longer an array in foreach, it becomes a variable.
Some information about html tags: https://www.w3schools.com/tags/
Also see how loop works: https://www.guru99.com/php-loop.html
Related
I have a PHP file that tries to echo a $_POST and I get an error, here is the code:
echo "<html>";
echo "<body>";
for($i=0; $i<5;$i++){
echo "<input name='C[]' value='$Texting[$i]' " .
"style='background-color:#D0A9F5;'></input>";
}
echo "</body>";
echo "</html>";
echo '<input type="submit" value="Save The Table" name="G"></input>'
Here is the code to echo the POST.
if(!empty($_POST['G'])){
echo $_POST['C'];
}
But when the code runs I get an error like:
Notice: Array to string conversion in
C:\xampp\htdocs\PHIS\FinalSubmissionOfTheFormPHP.php on line 8
What does this error mean and how do I fix it?
When you have many HTML inputs named C[] what you get in the POST array on the other end is an array of these values in $_POST['C']. So when you echo that, you are trying to print an array, so all it does is print Array and a notice.
To print properly an array, you either loop through it and echo each element, or you can use print_r.
Alternatively, if you don't know if it's an array or a string or whatever, you can use var_dump($var) which will tell you what type it is and what it's content is. Use that for debugging purposes only.
What the PHP Notice means and how to reproduce it:
If you send a PHP array into a function that expects a string like: echo or print, then the PHP interpreter will convert your array to the literal string Array, throw this Notice and keep going. For example:
php> print(array(1,2,3))
PHP Notice: Array to string conversion in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array
In this case, the function print dumps the literal string: Array to stdout and then logs the Notice to stderr and keeps going.
Another example in a PHP script:
<?php
$stuff = array(1,2,3);
print $stuff; //PHP Notice: Array to string conversion in yourfile on line 3
?>
Correction 1: use foreach loop to access array elements
http://php.net/foreach
$stuff = array(1,2,3);
foreach ($stuff as $value) {
echo $value, "\n";
}
Prints:
1
2
3
Or along with array keys
$stuff = array('name' => 'Joe', 'email' => 'joe#example.com');
foreach ($stuff as $key => $value) {
echo "$key: $value\n";
}
Prints:
name: Joe
email: joe#example.com
Note that array elements could be arrays as well. In this case either use foreach again or access this inner array elements using array syntax, e.g. $row['name']
Correction 2: Joining all the cells in the array together:
In case it's just a plain 1-demensional array, you can simply join all the cells into a string using a delimiter:
<?php
$stuff = array(1,2,3);
print implode(", ", $stuff); //prints 1, 2, 3
print join(',', $stuff); //prints 1,2,3
Correction 3: Stringify an array with complex structure:
In case your array has a complex structure but you need to convert it to a string anyway, then use http://php.net/json_encode
$stuff = array('name' => 'Joe', 'email' => 'joe#example.com');
print json_encode($stuff);
Prints
{"name":"Joe","email":"joe#example.com"}
A quick peek into array structure: use the builtin php functions
If you want just to inspect the array contents for the debugging purpose, use one of the following functions. Keep in mind that var_dump is most informative of them and thus usually being preferred for the purpose
http://php.net/print_r
http://php.net/var_dump
http://php.net/var_export
examples
$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);
Prints:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
array(3) {
[0]=>
int(3)
[1]=>
int(4)
[2]=>
int(5)
}
You are using <input name='C[]' in your HTML. This creates an array in PHP when the form is sent.
You are using echo $_POST['C']; to echo that array - this will not work, but instead emit that notice and the word "Array".
Depending on what you did with the rest of the code, you should probably use echo $_POST['C'][0];
Array to string conversion in latest versions of php 7.x is error, rather than notice, and prevents further code execution.
Using print, echo on array is not an option anymore.
Suppressing errors and notices is not a good practice, especially when in development environment and still debugging code.
Use var_dump,print_r, iterate through input value using foreach or for to output input data for names that are declared as input arrays ('name[]')
Most common practice to catch errors is using try/catch blocks, that helps us prevent interruption of code execution that might cause possible errors wrapped within try block.
try{ //wrap around possible cause of error or notice
if(!empty($_POST['C'])){
echo $_POST['C'];
}
}catch(Exception $e){
//handle the error message $e->getMessage();
}
<?php
ob_start();
var_dump($_POST['C']);
$result = ob_get_clean();
?>
if you want to capture the result in a variable
You can also try like this:
if(isset($_POST['G'])){
if(isset($_POST['C'])){
for($i=0; $i< count($_POST['C']); $i++){
echo $_POST['C'][$i];
}
}
}
I am requesting my output look like this:
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
The values are irrelevant for this example.
My code looks like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = $error_msg;
$temp_data = array();
$temp_value = '';
foreach ($zipcodes_array as $value) {
//$temp_data['zipcode'] = $value;
//$temp_value .= json_encode($temp_data);
$temp_value .= '{"zipcode":$value},';
}
//$returndata['test'] = $temp_value;
$returndata['zipcodes'] = $temp_value;
echo json_encode($returndata);
My output varies depending on my different attempts (which you can see with the commented out things) but basically, I don't understand how the 3rd part (the part with the zipcodes) doesn't have a key or a definition before the first open bracket "["
Here is the output for the code above:
{"error_num":0,"error_details":"","zipcodes":"{\"zipcode\":11111},{\"zipcode\":11112},{\"zipcode\":11113},{\"zipcode\":22222},{\"zipcode\":33333},{\"zipcode\":77325},{\"zipcode\":77338},{\"zipcode\":77339},{\"zipcode\":77345},{\"zipcode\":77346},{\"zipcode\":77347},{\"zipcode\":77396},{\"zipcode\":81501},{\"zipcode\":81502},{\"zipcode\":81503},{\"zipcode\":81504},{\"zipcode\":81505},{\"zipcode\":81506},{\"zipcode\":81507},{\"zipcode\":81508},{\"zipcode\":81509},"}
Obviously i did not show the variables being filled/created because its through MySQL. The values are irrelevant. Its the format of the output i'm trying to get down. I don't understand how they have the "zipcode": part in between {} brackets inside another section which appears to be using JSON_ENCODE
It is close but see how it still has the "zipcodes": part in there defining what key those values are on? My question is, is the "response" above being requested by a partner actually in JSON_ENCODE format?? or is it in some custom format which I'll just have to make w/out using any json features of PHP? I can easily write that but based on the way it looks in the example above (the response) I was thinking it was JSON_ENCODE being used.
Also, it keeps putting the \'s in front of the " which isn't right either. I know it's probably doing that because i'm json_encode'ing a string. Hopefully you see what i'm trying to do.
If this is just custom stuff made to resemble JSON, I apologize. I've tried to ask the partner but I guess i'm not asking the right questions (or the right person). They can never seem to give me answers.
EDIT: notice my output also doesn't have any [ or ] in it. but some of my test JSON_ENCODE stuff has had those in it. I'm sure its just me failing here i just cant figure it out.
If you want your output to look like the JSON output at the very top of your question, write the code like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = array();
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => (int)$value);
}
echo 'Response ' . json_encode($returndata);
This will return JSON formatted like you requested above.
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
Can you just use single ZipCode object as associative array, push all your small ZipCode objects to the ZipCodes array and encode whole data structure. Here is the code example:
$returndata = array(
'error_num' => $error_code,
'error_details' => array()
);
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => $value);
}
echo json_encode($returndata);
After googling, implementing code upon code, I still cannot get ANYTHING to display. Nothing. Not one thing.
I have a URL spitting out JSON:
{"videos":[{"video":{"name":"Sanyo Zio","youtube":"FxxLDr--R5A","post_date":"2010-10-08 01:00:00",...
Here's the code I'm using to access the page:
$url = file_get_contents("http://[website]/json/test.json");
$arr = json_decode($url,true);
Now here's a short list of what I've tried to access ANY data from the page:
1:
print_r($arr);
2:
foreach($arr['videos']['video'] as $item) {
echo "Name: ". $item[0] ."<br>";
}
3:
$obj = $arr[0];
echo $obj;
4:
foreach($arr as $a){
echo "Name: ".$a['videos']['video']['name']."<br />";
}
Clearly I'm missing something, but I just haven't been able to figure out what I'm doing wrong! Is my encoding not correct? Here's how I'm encoding the JSON to begin with:
$arr = array('videos' => array());
foreach($vid as $items){
$arr['videos'][] = array('video' => array(
'name' => $items['videoName'], 'youtube' => $items['youtubeID'], 'post_date' => $items['productionTimestamp'], 'description' => $items['videoDesc'], 'link' => $single_linker_values['deeplink'], 'image' => $image));
}
echo json_encode($arr);
Any ideas/suggestions?
Update - Apparently the server is locked down, but being inhouse I don't notice :) Obviously the webpage does! Thanks for the help!
From PHP Manual
NULL is returned if the json cannot be decoded or if the encoded data
is deeper than the recursion limit
Since you are not specifying a recursion limit, chances are that either your JSON is invalid or nothing is being retrieved from your URL.
Three things to try:
determine if there was a json_decode error
print_r(json_last_error()); // call after json_decode
check that data is being returned
print_r($url);
see if data will decode as an object
$obj = json_decode($url);
print_r($obj);
I'm having difficulty in retrieving values from a Json array. I have a Json dataset that has been created using json_encode. This is how it appears after using json_decode and displaying using print_r:
Array ( [0] => stdClass Object ( [postID] => 1961 [postTitle] => Kiss My Fairy [previewThumb] => 2011/09/Kiss-My-Fairy-Ibiza-essentialibiza-2011_feature.jpg [blogContent] => Ibiza has always had a flair for the extravagant, inhibitions are checked in at the airport when the floods of tourists arrive and the locals have embraced a freedom of partying that has turned the quiet Mediterranean island into the Mecca... ) ) a_post_data_array = 1
The code that achieves this is as follows:
$post_data_URL = "http://myurl.com/news/scrape/facebook-like-chart-ID.php?post_name=kiss-my-fairy";
$post_data_response = file_get_contents($post_data_URL);
$a_post_data_array=json_decode($post_data_response);
I now simply need to retrieve some of the values from this array to use as variables. The array will only ever have 1 set of values. I'm using the following code but it isn't working.
echo "**** -- " . $a_post_data_array[post_title] . "<br>";
Can anyone please help? I'm sorry this is so basic. I've been searching online but can't find any examples of this.
There are multiple issues with your code:
First you should instruct json_decode to give you a pure array with $data = json_decode($response, TRUE);
Then the result array is a list, and you have to access the first element as $data[0]
The entry you want to access has the key postTitle, not post_title as your example code showed. (And unless that's a predefined constant won't work.)
And you need to put those array keys in quotes, like print $data[0]["postTitle"];
Turn up your error_reporting level for some development help.
echo "** -- " . $a_post_data_array[0]['post_title'];
try this PHP code:
//$post_data_response = file_get_contents("https://raw.github.com/gist/1245028/80e690bcbe6f1c5b46676547fbd396ebba97339b/Person_John.json");
//$PersonObject = json_decode($post_data_response);
// Get Person Object from JSON Source
$PersonObject = json_decode('{"ID":"39CA2939-38C0-4C4E-AE6C-CFA5172B8CEB","lastname":"Doe","firstname":"John","age":25,"hobbies":["reading","cinema",{"sports":["volley-ball","snowboard"]}],"address":{}}');
// Get data from Object
echo "Person ID => $PersonObject->ID<br>";
echo "Person Name => $PersonObject->firstname<br>";
echo "Person Lastname => $PersonObject->lastname<br>";
echo "Person Age => $PersonObject->age<br>";
echo "Person Hobbies => " . $PersonObject->hobbies[0] . "<br>";
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo "$_GET[$field]";
echo "<br>";
}
print_r($datarray);
This is the output I am getting. I see the data is there in datarray but when
I echo $_GET[$field]
I only get "Array"
But print_r($datarray) prints all the data. Any idea how I pull those values?
OUTPUT
Array (
[0] => Array (
[0] => Grade1
[1] => ln
[2] => North America
[3] => yuiyyu
[4] => iuy
[5] => uiyui
[6] => yui
[7] => uiy
[8] => 0:0:5
)
)
EDIT: When I completed your test, here was the final URL:
http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24
This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like:
http://hofstrateach.org/Roberto/process.php?grade=Grade1&schoolname=Nathan®ion=North%20America&answer[]=5&answer[]=3&answer[]=no&answer[]=foo&answer[]=blat&time=0%3A0%3A24
This will create individual entries for most of the fields, and make $_GET['answer'] be an array of the answers provided by the user.
Bottom line: fix your Flash file.
Use var_export($_GET) to more easily see what kind of array you are getting.
From the output of your script I can see that you have multiple nested arrays. It seems to be something like:
$_GET = array( array( array("Grade1", "ln", "North America", "yuiyyu", "iuy", "uiyui", "yui","uiy","0:0:5")))
so to get those variables out you need something like:
echo $_GET[0][0][0]; // => "Grade1"
calling echo on an array will always output "Array".
print_r (from the PHP manual) prints human-readable information about a variable.
Use <pre> tags before print_r, then you will have a tree printed (or just look at the source. From this point you will have a clear understanding of how your array is and will be able to pull the value you want.
I suggest further reading on $_GET variable and arrays, for a better understanding of its values
Try this:
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo $_GET[$field]; // you don't really need quotes
echo "With quotes: {$_GET[$field]}"; // but if you want to use them
echo $field; // this is really the same thing as echo $_GET[$field], so
if($label == $_GET[$field]) {
echo "Should always be true<br>";
}
echo "<br>";
}
print_r($datarray);
It's printing just "Array" because when you say
echo "$_GET[$field]";
PHP can't know that you mean $_GET element $field, it sees it as you wanting to print variable $_GET. So, it tries to print it, and of course it's an Array, so that's what you get. Generally, when you want to echo an array element, you'd do it like this:
echo "The foo element of get is: {$_GET['foo']}";
The curly brackets tell PHP that the whole thing is a variable that needs to be interpreted; otherwise it will assume the variable name is $_GET by itself.
In your case though you don't need that, what you need is:
foreach ($_GET as $field => $label)
{
$datarray[] = $label;
}
and if you want to print it, just do
echo $label; // or $_GET[$field], but that's kind of pointless.
The problem was not with your flash file, change it back to how it was; you know it was correct because your $dataarray variable contained all the data. Why do you want to extract data from $_GET into another array anyway?
Perhaps the GET variables are arrays themselves? i.e. http://site.com?var[]=1&var[]=2
It looks like your GET argument is itself an array. It would be helpful to have the input as well as the output.