$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];
}
Related
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
I am updating my question with a few breakthroughs i was able to achieve today. I used get_object_vars.
This code was able to print out the value i am trying to iterate over.
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
print_r('<pre>'. print_r($arrayPid) .'</pre>');
This http://www.image-share.com/ijpg-1163-165.html is what i saw as a result.
Now since this Object has objects inside it along with the values i need i.e. FileID,FileName etc. I am seeing the error message but a glimpse of the output. The code i used was this (just a very minor change from the above. I used a foreach)
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
//print_r('<pre>'. print_r($arrayPid) .'</pre>');
foreach($arrayPid as $val) {
echo ($val);
echo "<br>";
}
}
As a result of this i saw the following output http://www.image-share.com/ijpg-1163-166.html .
The index number 1 occupies the object and hence the error for string conversion.
If i use a For loop instead of the foreach in the code just above,i am unable to print the values.
I tried:
for($i=0;$i<(count($arrayPid));$i+=1)
{
echo($arrayPid[$i]);
}
But this would print nothing.
Could any one help me with a way so that i can iterate and have the values inside that array $arrayPid.
Would like to have your suggestions, views, doubts on the same.
I am sorry that i am using imageshare but that is the only way i can share my screens.
Thanks
Angie
The correct way to use it is:
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//print_r($fileStatusObtained->FileID);
$fileId [] = $fileStatusObtained->FileID;
...
}
I am using PHP 5.3.6
I have the following code below. Everything works fine except for the last line which attempts to to return a value based on the position in the array as opposed to the associative name. Can anyone explain why this takes place and how I can build the array so that I can reference an item either by the associative name or position number?
Thanks.
<?php
class myObject {
var $Property;
function myObject($property) {
$this->Property = $property;
}
}
$ListOfObjects['form_a'] = new myObject(1);
$ListOfObjects['form_b'] = new myObject(2);
$ListOfObjects['form_c'] = new myObject(3);
$ListOfObjects['form_d'] = new myObject(4);
echo "<pre>";
print_r($ListOfObjects);
echo "</pre>";
echo "<hr />";
foreach ($ListOfObjects as $key => $val) {
echo "<li>" . $ListOfObjects[$key]->Property . "</li>";
}
echo "<hr />";
echo "<li>" . $ListOfObjects['form_a']->Property . "</li>"; // Works ok.
//Edit: ------------------------------------------------------------
//Edit: Everything above is for context only
//Edit: I'm only interested in the line below and why it does not work
//Edit: ------------------------------------------------------------
echo "<li>" . $ListOfObjects[0]->Property . "</li>"; //Does not work.
?>
function value_from_index($a,$k){
return array_slice($a,$k,1);
}
If you just want the first/last element of an array, try end($array) for the last item without destroying it and reset($array) to get the first.
Don't use reset and end if you're looping through an array as Flambino notes, this indeed results in some unexpected behaviour.
For anything inbetween you'll need to use array_slice()
Not the nicest way of doing it, but effektive and readable:
$i = 0;
$last = count($ListOfObjects);
foreach($ListOfObjects as $obj) {
if($i == 0) {
//do something with first object
$obj->property;
else if ($i == ($last-1)) {
//do something with last object
$obj->property;
}
}
PHP arrays aren't like arrays you know from most other programming languages, they are more like ordered hash tables / ordered dictionaries - they allow for access by named index and retain order when new items are added. If you want to allow access with numeric indices to such an array you have to define it that way or use one of roundabout ways given in other answers.
In your case you can use a single line of code to allow access by index:
$ListOfObjects += array_values($ListOfObjects);
This will extend your array with the same one but with numeric indices. As objects are always passed by reference, you can access the same object by writing $ListOfObjects['form_b'] and $ListOfObjects[1].
When sending data from a form to a second page, the value of the session is always with the name "Array" insteed of the expected number.
The data should get displayed in a table, but insteed of example 1, 2, 3 , 4 i get : Array, Array, Array.
(A 2-Dimensional Table is used)
Is the following code below a proper way to "call" upon the stored values on the 2nd page from the array ?
$test1 = $_SESSION["table"][0];
$test2 = $_SESSION["table"][1];
$test3 = $_SESSION["table"][2];
$test4 = $_SESSION["table"][3];
$test5 = $_SESSION["table"][4];
What exactly is this, and how can i fix this?
Is it some sort of override that needs to happen?
Best Regards.
You don't need any sort of override. The script is printing "Array" rather than a value, because you're trying to print to the screen a whole array, rather than a value within an array for example:
$some_array = array('0','1','2','3');
echo $some_array; //this will print out "Array"
echo $some_array[0]; //this will print "0"
print_r($some_array); //this will list all values within the array. Try it out!
print_r() is not useful for production code, because its ugly; however, for testing purposes it can keep you from pulling your hair out over nested arrays.
It's perfectly fine to access elements in your array by index: $some_array[2]
if you want it in a table you might do something like this:
<table>
<tr>
for($i = 0 ; $i < count($some_array) ; $i++) {
echo '<td>'.$some_array[$i].'</td>';
}
</tr>
</table>
As noted, try
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
That should show you what's in the session array.
A 2-dimensional table is just an array of arrays.
So, by pulling out $_SESSION["table"][0], you're pulling out an array that represents the first row of the table.
If you want a specific value from that table, you need to pass the second index, too. i.e. $_SESSION["table"][0][0]
Or you could just be lazy and do $table = $_SESSION["table"]; at which point $table would be your normal table again.
A nice way ...
<?php
foreach ($_SESSION as $key => $value) {
echo $key . " => " . $value . "<br>";
}
?>