Im new at this and not sure how to fill an array and echo it. Can someone please help me? :)
First my array, that I hope is retrieving info from my notes.txt-file, if there is any?! Im not sure if i need both declarations?:
$test = array();
$test[] = json_decode(file_get_contents($file), TRUE);
Anyway, this is the code for adding elements to the array, the input from the user:
$name = guestbook_input($_POST['name']);
$comment = guestbook_input($_POST['comment']);
$test[] = [
'name' => $name,
'comment' => $comment,
'ip' => $_SERVER['REMOTE_ADDR'],
'time' => date("y-m-d H:m")
];
// Write input to file
file_put_contents($file, json_encode($test));
This code works fine (I think) and writes to the file.
Finally Im trying to echo the array to a table like this:
<?php
$getfile = json_decode(file_get_contents('./notes.txt'), TRUE);
foreach ($getfile as $value): ?>
<tr>
<?php
echo '<td>';
echo $value['name'];
echo '</td>';
echo '<td>';
echo $value['comment'];
echo '</td>';
echo '<td>IP:';
echo $value['ip'];
echo "<br>Tid:";
echo $value['time'];
echo '</td>'?>
</tr> <?php endforeach; ?>
This code do print elements, but only for the first input in my guestbook. I have no idea if this is the right way to do this or not, but hopefully someone can help me with this, so I can get this right?!
First, your declaration and assignment:
$test = array();
$test[] = json_decode(file_get_contents($file), TRUE);
The function json_decode(), as you're calling it, returns an array, so it is not necessary to declare the variable first, but it is good practice to do so. However, in the function call, you are actually assigning the entire results to $test[0], since $test[] simply creates a new element with the next numeric index. The code where you assign the user input is correct, so it gets output correctly.
You are putting your array that you read from a file into a single element of the array $test.
Then you are adding your new entry as the second element.
You should initialise the array as:
$test = json_decode(file_get_contents($file), TRUE);
Related
I need to get data from a website and display in a table in my website. I am getting the data correctly but now just need to add it to a table so that it is more legible.
This is the code for some of the information I am getting:
echo "<div style='font-weight: bold;'>getProvinces</div>";
$args = array();
$args["strSessionId"] = $session;
$result = CurlFunction($args, "getProvinces");
echo '<pre>';
var_dump($result);
echo '</pre>';
And
case "getProvinces":
{
$Url = "https://apitest.axxess.co.za/" .
"calls/rsapi/getProvinces.json";
$curl->setBasicAuthentication($Username, $Password);
$curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
$curl->setOpt(CURLOPT_SSL_VERIFYHOST,2);
$curl->get($Url, $d);
break;
}
I just need some help on how to get the above info into a table. And if possible only sections. I have attached an image to show what I am getting at the moment as well as which data I would like to have in a Table format.
Thanks
Link to complete code I am using: https://transfernow.net/923hx9h1f2er
Use json_decode to obtain an array representing your response data, and use a foreach loop to create key-value pairs inside a table for each data item.
The code could look like:
$jsoned = json_decode($result, true)
?>
<table>
<?php foreach ($jsoned as $k => $v) {?>
<tr><td> <?=$k?> </td><td> <?=$v?> </td></tr>
<?php } ?>
btw, <?= $var ?> is a shortcut for <? echo $var; ?>
First of all, convert your json response into an array by using json_decode() like:
// assuming `$jsonResponse` is your json response variable
$decoded = json_decode($jsonResponse,true); // here true will use return response in array format
Then, you can use your response check like:
if($decoded['intCode'] == 200){
print_r($decoded['arrProvinceId']); // this will return you your response in array
}
now, you can you foreach() loop with html whatever you need with $decoded['arrProvinceId'] result.
I have an Array like this one:
Array ( [0] => a:39:{s:2:"id";s:6:"703981";s:4:"name";s:10:"Bilton Apt";s:7:"address";s:25:"Hart Blvd, Paradise Acres";s:3:"zip";s:2:"PO";s:10:"city_hotel";s:11:"Montego ....etc...
And i want to print in the page the "name" value so i wrote these two lines of code:
$item = get_post_meta($post->ID, '_ihfc_hotel');
echo $item['name'];
But when i load the page i receive this error:
Notice: Undefined index: name in /Applications/MAMP/htdocs/wp_test_csv/wp-content/themes/twenty....etc
i tried with other solutions like:
echo $item[0]['name']; or echo $item[0]->['name']:
But none works
Some one can help me?
You need to unserialize the array, as told in the comments:
$ar = unserialize($item[0]);
echo $ar['name'];
You can put it in a loop to get all values in a multi dimensional array:
foreach($item as $key=>$value){
$ar[$key] = unserialize($value);
}
and then access it:
echo $ar[0]['name'];
As Jon Stirling and u_mulder said, your array contains a serialized value and the only one shown in your example is index 0.
So due the fact that your example string is cut short with ....etc... I can only answer to what is known.
$data = unserialize($item[0]);
print_r($data);
echo $data['name'] // Bilton Apt
This should do that trick.
Did you mean:
<?php
$name = get_post_meta($post->ID, '_ihfc_hotel', true);
echo $name;
Otherwise
<?php
$data = get_post_meta($post->ID, '_ihfc_hotel', true);
$data = unserialize($data);
var_dump($data);
var_dump($data['name']);
I'm trying to parse a json file into a for each loop. The issue is the data is nested in containers with incremented numbers, which is an issue as I can't then just grab each value in the foreach. I've spent a while trying to find a way to get this to work and I've come up empty. Any idea?
Here is the json file tidied up so you can see what I mean - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json
I am trying to get values such as [number] but I also want to get deeper values such as [Driver][code]
<?php
// get ergast json feed for next race
$url = "http://ergast.com/api/f1/current/last/results.json";
// store array in $nextRace
$json = file_get_contents($url);
$nextRace = json_decode($json, TRUE);
$a = 0;
// get array for next race
// get date and figure out how many days remaining
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][' . $a++ . '];
foreach ($nextRaceDate['data'] as $key=>$val) {
echo $val['number'];
}
?>
While decoding the json there's no need to flatten the object to an Associative array. Just use it how it is supposed to be used.
$nextRace = json_decode($json);
$nextRaceDate = $nextRace->MRData->RaceTable->Races[0]->Results;
foreach($nextRaceDate as $race){
echo 'Race number : ' . $race->number . '<br>';
echo 'Race Points : ' . $race->points. '<br>';
echo '====================' . '<br>';
}
CodePad Example
You are nearly correct with your code, you are doing it wrong when you try the $a++. Remove the $a = 0, you won't need it.
Till here you are correct
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results']
What you have to do next is this
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'];
foreach($nextRaceDate as $key => $value){
foreach($value as $key2 => $value2)
print_r($value2);
So, in my code, you are stopping at Results, and then, you want to iterate over all the results, from 0 to X, the first foreach will do that, you have to access $value for that. So, add another foreach to iterate over all the content that $value has.
There you go, I added a print_r to show you that you are iterating over what you wanted.
The problem is how you access to the elements in the nested array.
Here a way to do it:
$mrData = json_decode($json, true)['MRData'];
foreach($nextRace['RaceTable']['Races'] as $race) {
// Here you have access to race's informations
echo $race['raceName'];
echo $race['round'];
// ...
foreach($race['Results'] as $result) {
// And here to a result
echo $result['number'];
echo $result['position'];
// ...
}
}
I don't know where come's from your object, but, if you're sure that you'll get everytime one race, the first loop could be suppressed and use the shortcut:
$race = json_decode($json, true)['MRData']['RaceTable']['Races'][0];
Your problem is that the index must be an integer because the array is non associative. Giving a string, php was looking for the key '$a++', and not the index with the value in $a.
If you need only the number of the first race, try this way
$a = 0;
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][$a];
echo "\n".$nextRaceDate['number'];
maybe you need to iterate in the 'Races' attribute
If you need all, try this way :
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races'];
foreach ($nextRaceDate as $key => $val) {
foreach ($val['Results'] as $val2) {
echo "\nNUMBER " . $val2['number'];
}
}
I am having a problem with getting data from json. I cant change the way it is saved in the database since it is generated by the framework and after that read for the fields generation. My json looks like this:
{"102":{"textinput":{"comment":"2"}},"104":"34"}
OR
{"78":{"textinput":{"comment":"1"}},"82":"34"}
Comment value is my serialnumber that I net to get from this json. I tried with :
$json_sn = json_decode($customer_json_sn, true);
$snr = $json_sn['78']['textinput']['comment'];
But this is not the solution I need, since I never know the value of first numeric key, I cant rely on that. Any help would be appreciated.
If this format is going to be always the same, you can use reset() function on this one. Consider this example:
$json_sn = json_decode($customer_json_sn, true);
$snr = reset($json_sn);
echo $snr['textinput']['comment'];
How about:
$snr_array = array()
foreach ($json_sn as $key)
snr_array[] = $key['textinput']['comment'];
Edit: I just realized that you might just need/get one comment:
$key = key($json_sn);
$snr = $json_sn[$key]['textinput']['comment'];
You can do:
<?php
$json = '{"78":{"textinput":{"comment":"1"}},"82":"34"}';
var_dump(json_decode($json, true));
$data = json_decode($json, true);
foreach( $data as $key => $value ) {
# Check if exsit
if (isset($value['textinput']['comment'])) {
echo "Value: " . $value['textinput']['comment'];
}
}
I am fairly new to PHP and programming in general... I am attempting to use a foreach loop to set some options on a page I have created. It all works except for the last section, where I am attempting to assign variables dynamically, so I can use them outside the loop.
<?PHP
$array=array(foo, bar, baz);
foreach ($array as $option) {
// I have if statements to determine what $option_req
// and $option_status end up being, they work correctly.
$option_req="Hello";
$option_status="World";
$rh='Req_';
$sh='Status_';
$$rh.$$option=$option_req;
$$sh.$$option=$option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
?>
When the loop is finished, should this now give me six variables?
$Req_foo
$Status_foo
$Req_bar
$Status_bar
$Req_baz
$Status_baz
I have played with this a bit, searches on Google seem fruitless today.
To access some array item, just access some array item.
No loops required.
$req = array("foo" => 1,
"bar" => 2,
"baz" => 3,
);
echo $req['foo'];
plain and simple
Looks like PHP doesn't like the concatenation when you're trying to do an assignment. Try doing so beforehand, like so:
<?php
$array = array('foo', 'bar', 'baz');
foreach ($array as $option)
{
$option_req="Hello";
$option_status="World";
$rh = 'Req_';
$sh = 'Status_';
$r_opt = $rh.$option;
$s_opt = $sh.$option;
$$r_opt = $option_req;
$$s_opt = $option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
As other commenters suggested, this isn't a great practice. Try storing your data in an array, rather than just cluttering up your namespace with variables.
You could (though you should not!) do:
${$rh.$option} = ...
Variable variables don't work that way. You need to have one variable containing the string.
$opt_r = $rh.$option;
$$opt_r = $option_req;
$opt_s = $sh.$option;
$$opt_s = $option_status;
Also, make sure to quote your strings:
$array=array('foo', 'bar', 'baz');
I don't suggest using variable variables, but if you want to, this is how to do it.