I need to output a JSON response using PHP5 that looks similar to the following:
{"success": true, "years": [{"yearnumber": 2012},{"yearnumber": 2013},...]}
I have gotten as far as:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=date('Y') ; $i < (date('Y')+21) ; $i++) {
$rt['years'][]= 'yearnumber:'.$i;
}
echo json_encode($rt);
Ofcourse this is not the proper way to achieve my goal - and it obviously doesn't produce the desired results.
I am fairly new to PHP programming and could use a little push here. Thanks.
To get this (The closest valid JSON that would be what I think you want):
{"success":true, "years":[2012,2013,...]}
You can use:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=intval(date('Y')) ; $i < (date('Y')+21) ; $i++) {
$rt['years'][]= $i;
}
echo json_encode($rt);
//{"success":true,"years":[2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024,2025,2026,2027,2028,2029,2030,2031,2032]}
For "years": [{"yearnumber": 2012}, {"yearnumber": 2013}]
You can use:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=intval(date('Y')) ; $i < (date('Y')+21) ; $i++) {
$rt['years'][]= array("yearnumber" => $i);
}
echo json_encode($rt);
//{"success":true,"years":[{"yearnumber":2012},{"yearnumber":2013},{"yearnumber":2014},{"yearnumber":2015},{"yearnumber":2016},{"yearnumber":2017},{"yearnumber":2018},{"yearnumber":2019},{"yearnumber":2020},{"yearnumber":2021},{"yearnumber":2022},{"yearnumber":2023},{"yearnumber":2024},{"yearnumber":2025},{"yearnumber":2026},{"yearnumber":2027},{"yearnumber":2028},{"yearnumber":2029},{"yearnumber":2030},{"yearnumber":2031},{"yearnumber":2032}]}
Though it appears redundant to me
This
{"success":true, "years":["yearnumber":2012,"yearnumber":2013,...]}
is not valid JSON. Arrays ([]) can't have keys in them, only values. The best solution (in this scenario) is to just cut they keys since they're all the same anyway (See Esailija's answer)
Another way would be to create an array of objects like this
{"success":true, "years":[{"yearnumber":2012},{"yearnumber":2013},...]}
To achieve that from PHP:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=intval(date('Y')) ; $i < (date('Y')+21) ; $i++) {
$rt['years'][] = array('yearnumber' => $i);
}
echo json_encode($rt);
Related
I'm having some doubt doing some for each loop, so i have an immense variable names ranging from $a1 - $a120
What I'm trying to do is doing a for each loop from where I can get each of thoose by using an indexing system.
$a116= "N69";
$a117= "V52";
$a118= "V53";
$a119= "V54";
$a120= "V55";
# FIM
for ($i = 0; $i <= 119; ++$i) {
$var = ${"a".$i}; // This is what i need to learn to do
$sheet->setCellValue($var, $array[$i]); // the array is other information im inserting to the file
}
It is not good for the loops. But you can use it, if you can not change your codes.
I just added
$var_name="a".$i;
$var = $$var_name;
And the full code is below.
$a116= "N69";
$a117= "V52";
$a118= "V53";
$a119= "V54";
$a120= "V55";
# FIM
for ($i = 0; $i <= 119; ++$i) {
$var_name="a".$i;
$var = $$var_name; // This is what i need to learn to do
$sheet->setCellValue($var, $array[$i]); // the array is other information im inserting to the file
}
You should update the code to use an array.
$data = [];
$data["a116"] = "N69";
$data["a117"] = "V52";
$data["a118"] = "V53";
$data["a119"] = "V54";
$data["a120"] = "V55";
Now you can use a foreach loop getting the key/value pairs
foreach($data as $key => $value){
$sheet->setCellValue($key, $value);
}
I am trying to make a JSON object out of multiple Array in PHP.
$a = array("Wis","Dex","Cha" );
$b = array(1,2,2);
$c = array("Perception","Stealth","Intimidation");
$d = array(8,5,1);
and I'm trying to get a bunch of JSON out of it such as this:
{ $c[0]:$d[0], "Stat":$a[0], "Multiplier:$b[0] };
and to get all those JSON and turn them in a string. But I've been trying to understand how json_encode works, but I cannot figure it out. I am hoping someone will be able to explain to me how to manipulate these values to turn them in JSON.
You can manually create the desired array using a for loop, then use json_encode on it. You have to be sure that the four arrays are the same size though.
$n = count($a);
$combined = array();
for ($i = 0; $i < $n; $i++) {
$entry = array();
$entry[$c[$i]] = $d[$i];
$entry["Stat"] = $a[$i];
$entry["Multiplier"] = $b[$i];
$combined[$i] = $entry;
}
$json = json_encode(combined);
How do you want the data to come out? As a JSON array of JSON object strings, or each string individually?
<?php
$a = array("Wis","Dex","Cha" );
$b = array(1,2,2);
$c = array("Perception","Stealth","Intimidation");
$d = array(8,5,1);
$data[$c[0]]=$d[0];
$data["Stat"]=$a[0];
$data["Multiplier"]=$b[0];
print(json_encode($data));
?>
Will give you something like
{"Perception":8,"Stat":"Wis","Multiplier":1}
If you want an array of those, then a few changes:
<?php
$a = array("Wis","Dex","Cha" );
$b = array(1,2,2);
$c = array("Perception","Stealth","Intimidation");
$d = array(8,5,1);
for($i=0;$i<count($a);$i++){
$data[$i][$c[$i]]=$d[$i];
$data[$i]["Stat"]=$a[$i];
$data[$i]["Multiplier"]=$b[$i];
}
print(json_encode($data));
?>
Which will give you something like
[{"Perception":8,"Stat":"Wis","Multiplier":1},
{"Stealth":5,"Stat":"Dex","Multiplier":2},
{"Intimidation":1,"Stat":"Cha","Multiplier":2}]
I'm using json_decode to parse JSON files. In a for loop, I attempt to capture specific cases in the JSON in which one element or another exist. I've implemented a function that seems to fit my needs, but I find that I need to use two for loops to get it to catch both of my cases.
I would rather use a single loop, if that's possible, but I'm stuck on how to get both cases caught in a single pass. Here's a mockup of what I would like the result to look like:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
//this is sometimes found 2nd
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") {
}
//this is sometimes found 1st
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") {
}
}
}
?>
Can anyone tell me how I could catch both cases outlined above within a single iteration?
I clearly could not do something like
if ($obj['patcher']['boxes'][$i]['box']['name'] == "string1" && $obj['patcher']['boxes'][$i]['box']['name'] == "string2") {}
...because that condition would never be met.
Generally what I do when I have raw data that is in an order that isn't ideal to work with is to run a first loop pass to generate a a list of indexes for me to pass through a second time.
So a quick example from your code:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
$index_mystring2 = array(); //Your list of indexes for the second condition
//1st loop.
$box_name;
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
$box_name = $obj['patcher']['boxes'][$i]['box']['name'];
if ( $box_name == "mystring1") {
//Do your code here for condition 1
}
if ($box_name == "mystring2") {
//We push the index onto an array for a later loop.
array_push($index_mystring2, $i);
}
}
//2nd loop
for($j=0; $j<=sizeof($index_mystring2); $j++) {
//Your code here. do note that $obj['patcher']['boxes'][$j]
// will refer you to the data in your decoded json tree
}
}
?>
Granted you can do this in more generic ways so it's cleaner (ie, generate both the first and second conditions into indexes) but i think you get the idea :)
I found that something like what #Jon had mentioned is probably the best way to attack this problem, for me at least:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
$found1 = $found2 = false;
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
//this is sometimes found 2nd
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") {
$found1 = true;
}
//this is sometimes found 1st
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") {
$found2 = true;
}
if ($found1 && $found2){
break;
}
}
}
?>
Could anyone help me.
I need to return multiple img's, but with this code, only one of two is returning.
What is the solution.
Thank you in advance.
$test = "/claim/img/box.png, /claim/img/box.png";
function test($test)
{
$photo = explode(',', $test);
for ($i = 0; $i < count($photo); $i++)
{
$returnas = "<img src=".$photo[$i].">";
return $returnas;
}
}
This might be a good opportunity to learn about array_map.
function test($test) {
return implode("",array_map(function($img) {
return "<img src='".trim($img)."' />";
},explode(",",$test)));
}
Many functions make writing code a lot simpler, and it's also faster because it uses lower-level code.
While we're on the subject of learning things, PHP 5.5 gives us generators. You could potentially use one here. For example:
function test($test) {
$pieces = explode(",",$test);
foreach($pieces as $img) {
yield "<img src='".trim($img)."' />";
}
}
That yield is where the magic happens. This makes your function behave like a generator. You can then do this:
$images = test($test);
foreach($images as $image) echo $image;
Personally, I think this generator solution is a lot cleaner than the array_map one I gave earlier, which in turn is tidier than manually iterating.
Modify your code that way
function test($test)
{
$returnas = '';
$photo = explode(',', $test);
for ($i = 0; $i < count($photo); $i++)
{
$returnas .= "<img src=".$photo[$i].">";
}
return $returnas;
}
Your code didn't work since you were returning inside the loop immediatly. Every programming language support "only a return for call". In my solution you're appendig a string that has an img tag each time you enter the loop and return it after every photo is "passed" into the loop
You could even use the foreach() construct, of course
Bonus answer
If you don't know the difference between ...
for ($i = 0; $i < count($photo); $i++)
and
for ($i = 0, $count = count($photo); $i < $<; $i++)
Well, in first case you'll evaluate count($photo) every single time the for is called whereas the second time, it is evaluated only once.
This could be used for optimization porpuses (even if php, internally, stores the length of an array so it is accesible in O(1))
The function breaks after the first return statement. You need to save what you want to return in some structure, an array eg, and return this.
function test($test)
{
$result = array();
$photo = explode(',', $test);
for ($i = 0; $i < count($photo); $i++)
{
$returnas = "<img src=".$photo[$i].">";
$result[] = $returnas;
}
return $result;
}
So I have fields that are generated dynamically in a different page and then their results should posted to story.php page. fields is going to be : *noun1 *noun2 *noun3 and story is going to be : somebody is doing *noun1 etc. What I want to do is to replace *noun1 in the story with the *noun, I have posted from the previous page ( I have *noun1 posted from the previous page ) but the code below is not working :
$fields = $_POST['fields'];
$story = $_POST['story'];
$fieldsArray = split(' ', $fields);
for ($i = 0; $i < count($fieldsArray); $i++) {
${$fieldsArray[$i]} = $_POST[$fieldsArray[$i]];
}
// replace words in story with input
for ($i = 0; $i < count($story); $i++) {
$thisWord = $story[$i];
if ($thisWord[0] == '*')
$story[$i] = ${$thisWord.substring(1)};
}
$tokensArray = split(' ',$tokens);
echo $story;
Your problem is likely that you are trying to echo $story, which I gather is an array. You might have better luck with the following:
$storyString = '';
for ($i = 0; $i < count($story); $i++)
{
$storyString .= $story[i] . ' ';
}
echo $storyString;
echo can't print an array, but you can echo strings to your heart's content.
You almost certainly don't want variable variables (e.g. ${$fieldsArray[$i]}). Also, $thisWord.substring(1) looks like you're trying to invoke a method, but that's not what it does; . is for string concatenation. In PHP, strings aren't objects. Use the substr function to get a substring.
preg_replace_callback can replace all your code, but its use of higher order functions might be too much to get into right now. For example,
function sequence($arr) {
return function() {
static $i=0
$val = $arr[$i++];
$i %= count($arr);
return $val;
}
}
echo preg_replace_callback('/\*\w+/', sequence(array('Dog', 'man')), "*Man bites *dog.");
will produce "Dog bites man." Code sample requires PHP 5.3 for anonymous functions.