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>";
}
Related
i have some problem with data array, how to replace spesific array column with searching in column id in array
data json array like this :
$json ='
[
{"id":1,"name":"Eko","approved":"n"},
{"id":2,"name":"Rudi","approved":"n"},
{"id":3,"name":"Yanto","approved":"n"}
]
';
ihave tried many tutorial but not spesific replace array
iwant output like this :
$json =
'
[
{"id":1,"name":"Eko","approved":"n"},
{"id":2,"name":"Rudi","approved":"y"},
{"id":3,"name":"Yanto","approved":"n"}
]
';
i apreciate with your help
defferent is "approved":"y" in json2
$array = json_decode($json);
foreach ($array as $key => $item) {
if($item->id == $your_serach_id){
$array[$key]->approved = "y";
}
}
I hope this helps.
You can tirverse the JSON object using for loop or foreach look and fetch the key value pair in the array and for getting your desired output you will need to know the value of which key you have to change so in the loop you can array[i] ->key = new_valuethis line should be thier after if condition in for loop
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'];
}
}
Ok, I have been fighting this for two days now!! Here is my Json structure.
[
{
"uuid":"/random number==",
"meeting_number":7196503037,
"host_id":"random number",
"topic":"My's Personal Meeting Room",
"start_time":"2015-01-06T22:01:07Z",
"timezone":"America/Denver",
"duration":56,
"total_size":378080,
"recording_count":1,
"recording_files":[
{
"id":"long number",
"meeting_id":"/NS90bsSTLeGzo6cT0nwXw==",
"recording_start":"2015-01-06T22:01:09Z",
"recording_end":"2015-01-06T22:01:14Z",
"file_size":378080,
"play_url":"https://myurl"
}
]
},
I am trying to pull the Start Time from the top level array (which is named 'meetings') and the Play Url from the second level array (recording_files). I am using json_decode to decode the file into arrays.
I have tried many variations found on this site and nothing seems to get to the play url.
VARIATION 1
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
foreach($key['recording_files'] as $subkey => $newvalue){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}}
This pulls an invalid argument in foreach.
VARIATION 2
foreach ($aha['meetings'] as $key => $value){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}
This pulls undefined index for play_url. As does the same code with the reference to ['recording_files'] placed before ['play_url']
VARIATION 3:
Then I tried giving up on the first level and just pulling data from the second level:
$aha = json_decode($response,true);
foreach ($aha['meetings']['recording_files'] as $key => $value){
echo '<p>Time : '.$value['recording_start'].'</p>
Recording<br>';
}
That gives me an undefined index on ['recording_files'] and a foreach error.
VARIATION 4.
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
$link=$key['recording_files'];
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}
This gets me the closest - no errors but no link. I presume that here the code is seeing the field but just not pulling the data from it...
Please help a newbie json person!!
If there is really an $aha['meetings'] (you don't show it), then use the value not the key in the second foreach:
foreach($aha['meetings'] as $value){
foreach($value['recording_files'] as $newvalue){
Final code that fixed it.
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';}
It was just a matter of finding the correct format for referencing the play_url piece.
Thank you so much to everyone!
Edit:
If your data looks like this :
$str = "{\"meetings\":[{
\"uuid\":\"/random number==\",
\"meeting_number\":7196503037,
\"host_id\":\"random number\",
\"topic\":\"My's Personal Meeting Room\",
\"start_time\":\"2015-01-06T22:01:07Z\",
\"timezone\":\"America/Denver\",
\"duration\":56,
\"total_size\":378080,
\"recording_count\":1,
\"recording_files\":[
{
\"id\":\"long number\",
\"meeting_id\":\"/NS90bsSTLeGzo6cT0nwXw==\",
\"recording_start\":\"2015-01-06T22:01:09Z\",
\"recording_end\":\"2015-01-06T22:01:14Z\",
\"file_size\":378080,
\"play_url\":\"https://myurl\"
}
]
}]}";
$json = json_decode($str);
$res = $json->{'meetings'};
foreach($res as $keys){
echo $keys->{'start_time'}."<br>";
foreach ($keys->{'recording_files'} as $data){
echo $data->{'play_url'}."<br>";
echo $data->{'recording_start'}."<br>";
}
}
I am trying to pass an array of values through a form submission. As an example:
example.com?value1=178&value2=345&value3=2356
The easy solution would be for me to do the following to get the values on the new page:
$value1=$_GET['value1'];
$value2=$_GET['value2'];
$value3=$_GET['value3'];
The difficulty that I am having is that the variable after the word 'value' passed through the form will change with each submission. So I have amended the code to pass as:
example.com?value14=178&variable=14&value23=345&variable=23&value63=2356&variable=63
As you can see here, I have now passed the variable that comes in from of the value as a GET parameter. My attempt then GET these values to display individually on the submitted page is as follows:
$variable=$_GET['variable'];
$value=$_GET['value'.$variable];
echo $value . '<br>';
This code almost works. I am able to get the last array which is passed through to display. How can I fix this code to get all of the passed values to display on the submitted page?
Use PHP's array notation for form fields:
val[]=178&val[]=14&val[]=345&etc...
This will cause $_GET['val'] to be an array:
$_GET = array(
'val' => array(178, 14, 345, etc...)
)
If you can't rearrange the URL like that, you can try using preg_grep:
$matches = preg_grep('/^variable\d+$/', array_keys($_GET));
which'll return :
$matches= array('variable1', 'variable2', 'variable3', etc...);
Use an array, for example like this without the need for variable $variable.
example.com?value[14]=178&value[23]=345&value[63]=2356
foreach ($_GET['value'] as $key => value) {
echo $key . " => " . $value . "<br/>";
}
EDIT: Another way for getting the values would be looping the whole $_GET -array and parsing values from there like this (variables are always in the form of "value" followed by X numbers):
example.com?value14=178&value23=345&value63=2356
$values = array();
foreach ($_GET as $key => $value) {
if (preg_match('/^value[\d]+$/', $key)) {
// remove "value" from the beginning of the key
$key = str_replace('value', '', $key);
// save result to array
$values[$key] = $value;
}
}
See http_build_query()
I'm developing a php app that uses a database class to query MySQL.
The class is here: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/*note there are multiple bad practices demonstrated in the tutorial -- it should not be used as a modern guide!
I made some tweaks on the class to fit my needs, but there is a problem (maybe a stupid one).
When using select() it returns a multidimensional array that has rows with 3 associative columns (id, firstname, lastname):
Array
(
[0] => Array
(
[id] => 1
[firstname] => Firstname one
[lastname] => Lastname one
)
[1] => Array
(
[id] => 2
[firstname] => Firstname two
[lastname] => Lastname two
)
[2] => Array
(
[id] => 3
[firstname] => Firstname three
[lastname] => Lastname three
)
)
Now I want this array to be used as a mysql result (mysql_fetch_assoc()).
I know that it may be used with foreach(), but this is with simple/flat arrays. I think that I have to redeclare a new foreach() within each foreach(), but I think this could slow down or cause some higher server load.
So how to apply foreach() with this multidimensional array the simplest way?
You can use foreach here just fine.
foreach ($rows as $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
I think you are used to accessing the data with numerical indices (such as $row[0]), but this is not necessary. We can use associative arrays to get the data we're after.
You can use array_walk_recursive:
array_walk_recursive($array, function ($item, $key) {
echo "$key holds $item\n";
});
With arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:
foreach($my_array as $number => $number_array)
{
foreach($number_array as $data = > $user_data)
{
print "Array number: $number, contains $data with $user_data. <br>";
}
}
This would have been a comment under Brad's answer, but I don't have a high enough reputation.
Recently I found that I needed the key of the multidimensional array too, i.e., it wasn't just an index for the array, in the foreach loop.
In order to achieve that, you could use something very similar to the accepted answer, but instead split the key and value as follows
foreach ($mda as $mdaKey => $mdaData) {
echo $mdaKey . ": " . $mdaData["value"];
}
Hope that helps someone.
Holla/Hello,
I got it! You can easily get the file name,tmp_name,file_size etc.So I will show you how to get file name with a line of code.
for ($i = 0 ; $i < count($files['name']); $i++) {
echo $files['name'][$i].'<br/>';
}
It is tested on my PC.
To get detail out of each value in a multidimensional array is quite straightforward once you have your array in place. So this is the array:
$example_array = array(
array('1','John','Smith'),
array('2','Dave','Jones'),
array('3','Bob','Williams')
);
Then use a foreach loop and have the array ran through like this:
foreach ($example_array as $value) {
echo $value[0]; //this will echo 1 on first cycle, 2 on second etc....
echo $value[1]; //this will echo John on first cycle, Dave on second etc....
echo $value[2]; //this will echo Smith on first cycle, Jones on second etc....
}
You can echo whatever you like around it to, so to echo into a table:
echo "<table>"
foreach ($example_array as $value) {
echo "<tr><td>" . $value[0] . "</td>";
echo "<td>" . $value[1] . "</td>";
echo "<td>" . $value[2] . "</td></tr>";
}
echo "</table>";
Should give you a table like this:
|1|John|Smith |
|2|Dave|Jones |
|3|Bob |Williams|
Example with mysql_fetch_assoc():
while ($row = mysql_fetch_assoc($result))
{
/* ... your stuff ...*/
}
In your case with foreach, with the $result array you get from select():
foreach ($result as $row)
{
/* ... your stuff ...*/
}
It's much like the same, with proper iteration.
Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps
$response = array();
foreach ($res as $result) {
$elements = array("firstname" => $result[0], "subject_name" => $result[1]);
array_push($response, $elements);
}
I know this is quite an old answer.
Here is a faster solution without using foreach:
Use array_column
print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'
Also you can check before executing the above operation
if(array_key_exists('firstname', $array)){
print_r(array_column($array, 'firstname'));
}
Wouldn't a normal foreach basically yield the same result as a mysql_fetch_assoc in your case?
when using foreach on that array, you would get an array containing those three keys: 'id','firstname' and 'lastname'.
That should be the same as mysql_fetch_assoc would give (in a loop) for each row.
foreach ($parsed as $key=> $poke)
{
$insert = mysql_query("insert into soal
(pertanyaan, a, b, c, d, e, jawaban)
values
('$poke[question]',
'$poke[options][A]',
'$poke[options][B]',
'$poke[options][C]',
'$poke[options][D]',
'$poke[options][E]',
'$poke[answer]')");
}
If you need to do string manipulation on array elements, e.g, then using callback function array_walk_recursive (or even array_walk) works well. Both come in handy when dynamically writing SQL statements.
In this usage, I have this array with each element needing an appended comma and newline.
$some_array = [];
data in $some_array
0: "Some string in an array"
1: "Another string in an array"
Per php.net
If callback needs to be working with the actual values of the array,
specify the first parameter of callback as a reference. Then, any
changes made to those elements will be made in the original array
itself.
array_walk_recursive($some_array, function (&$value, $key) {
$value .= ",\n";
});
Result:
"Some string in an array,\n"
"Another string in an array,\n"
Here's the same concept using array_walk to prepend the database table name to the field.
$fields = [];
data in $fields:
0: "FirstName"
1: "LastName"
$tbl = "Employees"
array_walk($fields, 'prefixOnArray', $tbl.".");
function prefixOnArray(&$value, $key, $prefix) {
$value = $prefix.$value;
}
Result:
"Employees.FirstName"
"Employees.LastName"
I would be curious to know if performance is at issue over foreach, but for an array with a handful of elements, IMHO, it's hardly worth considering.
A mysql result set object is immediately iterable within a foreach(). This means that it is not necessary to call any kind of fetch*() function/method to access the row data in php. You can simply pass the result set object as the input value of the foreach().
Also, from PHP7.1, "array destructuring" allows you to create individual values (if desirable) within the foreach() declaration.
Non-exhaustive list of examples that all produce the same output: (PHPize Sandbox)
foreach ($mysqli->query("SELECT id, firstname, lastname FROM your_table") as $row) {
vprintf('%d: %s %s', $row);
}
foreach ($mysqli->query("SELECT * FROM your_table") as ['id' => $id, 'firstname' => $firstName, 'lastname' => $lastName]) {
printf('%d: %s %s', $id, $firstName, $lastName);
}
*note that you do not need to list all columns while destructuring -- only what you intend to access
$result = $mysqli->query("SELECT * FROM your_table");
foreach ($result as $row) {
echo "$row['id']: $row['firstname'] $row['lastname']";
}