I have an array in javascript that I need to join and send through a URL to PHP such as the following:
var objects = [];
objects.splice("red",0,"apple");
objects.splice("yellow",0,"banana");
objects.splice("purple",0,"grape");
var string = objects.join("+");
$("#print_div").load("fruits.php?fruits=" + string);
In PHP, I want to recieve the string and convert it back to an array... something like this:
$fruits = explode(" ", $_REQUEST['fruits']);
foreach($fruits as $key => $value){
echo "The " . $value . " is " . $key;
}
Maybe it is the join or the splice in javascript that wont make this work, or maybe the explode in php. Im not sure, but I need a solution to be able to create custom indexes to an array in javascript and then send to php and still be able to access the index and value names.
Thanks for your help!
If you use objects.join("+") in javascript you should use explode("+", $_REQUEST['fruits']) in PHP
Try using push() to add elements to an array.
You may want to look into parse_str which takes a GET string and parses it into an array, keyed and everything.
Suppose this is your object:
var fruits = {
red: "apple",
yellow: "banana",
purple: "grape"
};
Pass it to php like so: (ref)
$("#print_div").load("fruits.php", {fruits: fruits});
Use it like so:
$fruits = $_REQUEST['fruits'];
foreach($fruits as $key => $value){
echo "The " . $value . " is " . $key;
}
You are using splice wrong. Check it here.
You could pass the data to the .load method like below, it's much simple.
var data = {
"red": "apple",
"yellow": "banana",
"purple": "grape"
};
$("#print_div").load("fruits.php", data);
And in php:
foreach($_GET as $key => $value){
echo "The " . $value . " is " . $key;
}
Even if you change nothing else in the original code, this line
$("#print_div").load("fruits.php?fruits=string");
should probably be
$("#print_div").load("fruits.php?fruits="+string);
Related
I have made a GET call through an API and received data that originally looked like this:
{"#odata.context":"API-URL-CALL","value":[{"Id":1,"Name":Bill"},{"Id":2,"Name":Ted"}]
I took this data and altered it to look like this:
array("Id"=>1,"Name"=>"Bill","Id"=>2,"Name"=>"Ted");
What I am trying to do is echo this all out but so far I have only been able to get the second Id and Name to print out.
My code is as follows:
<?php
$my_array = array("Id"=>1,"Name"=>"Bill","Id"=>2,"Name"=>"Ted");
foreach($my_array as $key => $value)
{
echo
"
$key = $value <br>
";
}
?>
As stated above this only prints out:
Id = 2
Name = Ted
I feel like this is a simple fix and I have looked at many posts but can't seem t find the proper fix for this. I have tried things such as:
$key = $value[0] <br>
$key = $value[0][Id] <br>
foreach($my_array as $arr)
echo
"
id = $arr[Id], <br>
name = $arr[Name]
"
foreach($my_array as $arr)
echo
"
id = $arr[0][Id], <br>
name = $arr[0][Name]
"
All these ever get me are a single character or nothing at all. Like I said before I feel like this is a simple fix and I'm overlooking something or not adding something? Any help or advise or even a link to another post would be much appreciated. Thank you for your time :^D
Not sure how you achieved your second array from the initial JSON (although that has a few errors in the format), but you have flattened the array into a single array which has duplicate keys (and will only end up with the last value).
If you try
print_r(array("Id"=>1,"Name"=>"Bill","Id"=>2,"Name"=>"Ted"));
you would see the data ends up as
Array
(
[Id] => 2
[Name] => Ted
)
To extract the data properly, you need to decode the JSON (corrected JSON in the code) and then extract the data...
$json = '{
"#odata.context": "API-URL-CALL",
"value": [
{
"Id": 1,
"Name": "Bill "
},
{
"Id": 2,
"Name": "Ted"
}
]
}';
$my_array = json_decode($json, true);
foreach ( $my_array['value'] as $arr) {
echo "
id = $arr[Id], <br>
name = $arr[Name]
";
}
You have to put quotes around index names.
foreach($my_array as $arr)
echo '
id = '.$arr['Id'].', <br>
name = '.$arr['Name'].'
';
This happens because you defined associative array. This type of array use key=>value pairs. In this type of array keys should be unique.
Because you used none unique keys for example Id and Name, Every time you insert a value to array it overwrite previous values. So every time you loop through array it just shows last overwrote value.
To fix the problem you should use array inside array:
$my_array = array(array("Id"=>1,"Name"=>"Bill"),array("Id"=>2,"Name"=>"Ted"));
foreach($my_array as $array)
{
echo "{$array['Id']} = {$array['Name']} <br>";
}
I need to get values of array through a loop with dynamic vars.
I can't understand why the "echo" doesn’t display any result for "$TAB['b']".
Do you know why ?
The test with error message : https://3v4l.org/Fp3GT
$TAB_a = "aaaaa";
$TAB['b'] = "bbbbb";
$TAB['b']['c'] = "ccccc";
$TAB_paths = ["_a", "['b']", "['b']['c']"];
foreach ($TAB_paths as $key => $value) {
echo "\n\n\${'TAB'.$value} : "; print_r(${'TAB'.$value});
}
You are treating the array access characters as if they are part of the variable name. They are not.
So if you have an array $TAB = array('b' => 'something');, the variable name is $TAB. When you do ${'TAB'.$value}, you're looking for a variable that's actually named $TAB['b'], which you don't have.
Since you say that you just want to be able to access array indexes dynamically based on the values in another array, you just put the indexes alone (without the array access characters) in the other array.
$TAB['b'] = 'bbbbbb';
$TAB['c'] = 'cccccc';
$TAB_paths = array('b', 'c');
foreach ($TAB_paths as $key => $value) {
echo "\n\n".'$TAB['."'$value'".'] : ' . $TAB[$value];
}
Output:
$TAB['b'] : bbbbbb
$TAB['c'] : cccccc
DEMO
It's unclear what you're trying to do, although you need to include $TAB_all in $TAB_paths:
$TAB_paths = [$TAB_all['a'], $TAB_all['aside']['nav']];
Result:
${TAB_all.aaaaa} : ${TAB_all.bbbbb} :
Not certain what you're needing. My guess you need to merge two arrays into one. Easiest solution is to use the array_merge function.
$TAB_paths = array_merge($TAB_a1, $TAB_a2);
You can define the variable first
foreach ($TAB_all as $key => $value) {
${"TAB_all" . $key} = $value;
}
Now Explore the result:
foreach ($TAB_all as $key => $value) {
print_r(${"TAB_all" . $key});
}
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 a little rusty on my PHP and I am trying to create a function that will build an array. Essentially, I am trying to have an associative array of contacts ($contacts), with each individual element being a separate array ($contact). For starters, I would like it to be able to have a UniqueID,FirstName,and LastName within the elements. Here is the direction I am heading in right now:
<?php
$contact=array();
function createContact($Unique_ID,$FirstName,$LastName){
global $contact;
$contact=array("Unique_ID"=>$Unique_ID,"First_Name"=>$FirstName,"Last_Name"=>$LastName);
};
createContact("123456","John","Smith");
createContact("654321","Jane","Doe");
createContact("331143","Steve","Sample");
foreach($contact as $key=>$value){
echo $key.",",$value."<br>";
};
?>
This should create the $contact array with 3 separate records, but it only adds the last entry (In this case Steve Sample because it is the last one that was run). I remember learning somewhat about the global variables, but I think I am using it incorrectly. After I solve this, I will find a way to make an array containing all of these arrays.
You are overwriting the array $contact every time you invoke createContact().
You have to append the new records
function createContact($Unique_ID,$FirstName,$LastName){
$contact[] = array("Unique_ID" => $Unique_ID, "First_Name" => $FirstName, "Last_Name" => $LastName);
};
Note the [] to indicate that you want to append another entry.
If you want to print these you probably want to do something like this
foreach ($contact as $item) {
echo "ID = " . $item["Unique_ID"] . "<br>";
echo "First name = " . $item["First_Name"] . "<br>";
echo "Last name = " . $item["Last_Name"] . "<br>";
}
You need additional array.
$final_array = array();
and use
array_push($final_array, $contact);
inside the createContact function
$icecream = array (
"Choco" => array('2 Dollars'),
"Mango" => array('3 Dollars')
);
print $icecream[0][0];
expected output:
2 Dollars
Edit: I have a huge list of icecream sorts and i do want to use a loop to output all the information as a HTML DOM. So I do not want to go through each array value and echo it with the explicit value (i.e. 'Choco', 'Orange', etc...).
I want to use values as keys for the "first array level" ($icecream[0]),
It does output nothing at all. What is my logical flaw with this solution?
try this:
echo $icecream['Choco'][0]
Your problem here is calling the wrong key for the 1st dim
.
.
For your updated question, try this:
$ice_k = array_keys($icecream);
echo $icecream[$ice_k[0]][0];
You're not using the associative array right. You need to use the right key.
echo $icecream['choco'][0];
You can use position but it will be a counter like this:
$counter = 0;
foreach($icecream As $k=>$v) {
echo $icecream[$k][0] . ' [' . $counter . ']';
$counter++;
}
and if you want to get only value you can use previous code
$ice_k = array_keys($icecream);
$position = 5;
if( isset($ice_k[$position]) ) {
echo $icecream[$ice_k[$position]][0];
}