Foreach data list from array - incrementing numbers - php

I am trying to create a option list from a JSON decoded API link.
So far I have the access to the API sorted, all the data I need stored in a single variable and can extract data from the variable using
print_r($result[0]["ORGANISATION_NAME"]);
print_r($result[1]["ORGANISATION_NAME"]);
This will give me two different Organisation names from the array.
What I would like to do is put this in an alphabetical drop down menu, but for some reason I cannot for the life of me get foreach to work. All we need to do is increment the 0,1,2,3 etc to the number of records stored in the database.
I have no idea on how to do that !

To answer your question as asked:
foreach ($results as $result) {
for ($i = 0; $i < count($result); $i++) {
print_r($result[$i]["ORGANISATION_NAME"]);
}
}
However, why not just another foreach?
EDIT:
Updating based off of new info:
Assuming $result is your DB result here is your new code:
foreach ($result as $row) {
print_r($row['ORGANISATION_NAME']);
}

I think a couple of sensible steps of data preparation will help to simplify this task for you.
Isolate the desired column of data and create a new 1-dimensional array of organization names.
Sort the names alphabetically.
Then you can use a simple foreach loop to generate the html select field.
Code (Demo)
$result = [
["ORGANISATION_NAME" => "B Name"],
["ORGANISATION_NAME" => "D Name"],
["ORGANISATION_NAME" => "C Name"],
["ORGANISATION_NAME" => "A Name"]
];
echo "Proof of correct structure: {$result[1]["ORGANISATION_NAME"]}\n";
$org_names = array_column($result, "ORGANISATION_NAME");
sort($org_names);
var_export($org_names); // display alphabetized array
echo "\n---\n";
echo "<select name=\"orgs\">";
foreach ($org_names as $org) {
echo "<option>$org</option>";
}
echo "</select>";
Output:
Proof of correct structure: D Name
array (
0 => 'A Name',
1 => 'B Name',
2 => 'C Name',
3 => 'D Name',
)
---
<select name="orgs">
<option>A Name</option>
<option>B Name</option>
<option>C Name</option>
<option>D Name</option>
</select>

Related

For loop in php code needs an explanation

<!-- 1- create a new file called lab3.php
2- add the HTML skeleton code and give its title “Lab Week 3”
3- open up an php scope
4- Create an associative array listing favourite subjects. (example: math, english, science and grade for each A+ B+ C- )
5- print out for grade english subject
6- using a for loop print all the items in the array
-->
>
<?php
//Code for associative array
//data for associated array
$subjects = [
"math" => "A+",
"english" => "B+",
"science" => "C-",
]
<br>
// Code to print out english grade
//print out for english grade
echo "My grade in english class is" . $subjects["english"];
<br>
// This is my for loop section. If anyone could help me figure this out I'd be greatly appreciated.
//print out all the items in the array using for loop
for ($x=0; <= 2){
echo "$subjects[$x]";
}
?>
For all the items in your array use foreach instead:
foreach ($subjects as $subject => $grade) {
echo 'My grade in '.$subject. ' is '. $grade . PHP_EOL;
}
BTW: 1. Don't forget to remove <br> tags in your php code.
You cannot use for loop here, since your array does not have numeric array keys, and if you run for loop in the way you showed in your code, you will get undefined array key warnings.
Try it online!

Get Records From Array Based On Value

Bottom line, I have a huge multidimensional array returned by ldap_get_entries that I am trying to parse into different groups based on the location attribute.
In PowerShell I could do something like:
$location1 = Get-ADUser -Filter * | ? {?_.l -eq "test_location"}
What I am currently doing within PHP (as far as my brain will let me go) is something like:
Foreach ($records as $record) {
if (isset($record['l'])) {
switch ($record['l'][0]) {
case "test_location1":
$location1[] = $record;
continue 2;
case "test_location2":
$location2[] = $record;
continue 2;
}
}
}
I then use a foreach loop (alternative syntax) against an array of location variables ($location1, $location2), that I used the above method, to sort records into their appropriate location variable. In this way, I build an HTML table grouping each locations records together. I build a new table for each location with some HTML code in between each group, so I don't believe sorting the ldap results by location will work, as it would output one large table.
Is there any way to specify a WHERE clause in PHP? So that I can assign all records in an array with a matching key value to variable1 and all records in an array with a different matching key value to variable2.
I am assuming I am tackling this in an amateur scripting way.. If there is an easier way to accomplish this task (maybe skipping the assign records to variables part), or any sort of "best practice" I am missing here, I am up for learning it.
Thanks in advance!!
As far as I understood your question you want something like this:
$recordsSorted = array();
foreach ($records as $record) {
if (! isset($record['l'])) {
continue;
}
$recordsSorted[$records['l'][0]][] = $record;
}
ksort($recordsSorted);
foreach($recordsSorted as $location => $records) {
usort($records, function($a, $b){
return strnatcasecmp($a['uid'][0], $b['uid'][0]);
});
echo '<h1>$location</h1><ul>';
foreach ($records as $record) {
echo '<li>' . $record['dn'] . '</li>';
}
echo '</ul>';
}
This will first put the first entry to the location-attribute of an entry as key of an array. That key can then be used to sort the array.
To output the content then it iterates over the new array and sorts the content - in this case using the first value of the uid-attribute (change the uid to whatever attribute you need). This sorted content is then output to HTML.
the first array $recordsSorted might look somewhat like this:
array(
'London' => array(
array(<entry from the LDAP>),
array(<another entry from LDAP>),
),
'Paris' => array(
array(<a further entry from the LDAP>),
),
'Berlin' => array(
array(<and even another entry from the LDAP>),
),
);
The result would then look somewhat like this:
<h1>Berlin</h1>
<ul>
<li>[UID of and even another entry from the LDAP]</li>
</ul>
<h1>London</h1>
<ul>
<li>[UID of another entry from LDAP]</li>
<li>[UID of entry from the LDAP]</li>
</ul>
<h1>Paris</h1>
<ul>
<li>[UID of a further entry from the LDAP]</li>
</ul>
Does that look like it could help you?

PHP display JSON and XML

I am making use of an available API to send requests and receive the results which is in json and xml formats. I am able to do so but how do I display the returned data properly?
I used json_decode and assign the xml data to an array and print_r those. It shows up in a huge junk of data.
How do I show it on a table form? Or must I save the data into individual files or database first before displaying?
I am new to PHP, thus not sure how to implement this.
JSON is a multidimensional-array, the easiest way to view it, in my opinion, is to just
var_dump($json_array);
Though, this may be the chunk of data you're referring to.
It's not a very table friendly format, as a table is inherently 2-dimensional, and JSON can be many-dimensional.
You can flatten the array, and then display it as a table.
function flatten_json($json, &$flat, $key) {
// First check the base case: if the arg is not an array,
// then it's data to be inserted in the flat array.
if (!is_array($json)) {
$flat[$key] = $json;
} else {
// It's an array, to reduce the depth of the json,
// we remove this array, by iterating through it,
// sending the elements to be checked if they're also arrays,
// or if they're data to be inserted into the flat array.
foreach ($json as $name => $element) {
flatten_json($element, $flat, $key.'_'.$name);
}
}
}
To use this function, you first declare you flat array:
$flat = array();
Then pass it to the function, with your json, and a key you want to be the outer key, if you are sure that your json is an array, which is pretty much guaranteed, you can leave the key empty.
flatten_json($json_array, $flat, '');
Now $flat will have the flattened json, and you can print it as a table, maybe into a csv if you have many json results to print.
If your json was:
array(
'person' => array(
'name' => 'timmy',
'age' => '5'
),
'car' => array(
'make' => 'ford',
'engine' => array(
'hp' => 260,
'cyls' => 8
)
)
)
Then $flat will look like:
array(
'person_name' => 'timmy',
'person_age' => 5,
'car_make' => 'ford',
'car_engine_hp' => 260,
'car_engine_cyls' => 8
)
and if you wanted printed in a nice html table:
echo "<table><tr>";
foreach ($flat as $header => $value) {
echo "<th>$header</th>;
}
echo "</tr><tr>";
foreach ($flat as $header => $value) {
echo "<td>$value</td>";
}
echo "</tr></table>";
I am slight confuse. but if you're referring to an xml file that will appear somethign like this :
<books>
<book published="2011-07-24 19:40:26">
<title>I left my heart on Europa</title>
<author>Ship of Nomads</author>
< /book>
<book published="2011-07-24 19:40:26">
<title>I left my liveron Europa</title>
<author>Ship of Nomads</author>
< /book>
</books>
You can do some php trick here by using simplexml_load_file.
Example from the above xml you can have this code :
$mybooks= simplexml_load_file('books.xml');
echo "<ul id="booklist">";
foreach ($mybooks as $bookinfo):
$title=$bookinfo->title;
$author=$bookinfo->author;
$date=$bookinfo['published'];
echo "<li><div class="title">".$title."</div><div class="author">by ".$author."</div><b>".$date."</b></li>";
endforeach; echo "</ul>";
Hope this helps.

Separating data in array where duplicates are present using foreach loop in PHP

I have a database table with one column that will be options and another column that respresents the option values for that option. Example:
Options: Option Values
Color - Red
Color - Blue
Size - Large
Size - Small
How do I loop through the data to where I can populate a select box where the options are grouped like:
Color:
Red
Blue
Size:
Large
Small
Thanks in advance!
If you want to display <select> box for each, I would do something like the following :-
( being sure to ORDER BY 'Options' or similar depending on your database )
$previous_option = "";
$count = 0;
foreach($data as $row){
if($row['options'] != $previous_option){
if($count>0){
echo '</select>'.$row['options'].': <select name="'.$row['options'].'">';
} else {
echo $row['options'].': <select name="'.$row['options'].'">';
}
}
echo '<option>'.$row['value'].'</option>';
$count++;
$previous_option = $row['options'];
}
$data = your database result.
$row['options'] = database column 'options'.
$row['value'] = database column 'options values'
$previous_option = used for option "grouping"
$count = used for tracking first iteration
Loop over each row, and use PHP's [] array operator and your option name as a key to a multi-dimensional array.
foreach($yourRows as $data) {
if (!isset($options[$data['option']])) {
$options[$data['option']] = array();
}
$options[$data['option']][] = $data['value'];
}
This will make a two-dimensional array, where the first level is associative, keyed on the option names, and each of those keys contains a numerically-indexed array of that option's values.
The resulting array will look it was created like this:
$options = array(
"color" => array("red", "blue"),
"size" => array("small", "large")
);
then iterate like this over the options as needed:
echo '<select name="options" multiple="multiple">';
foreach($options as $option_type => $available_options) {
printf('<optgroup label="%s">', $option_type);
foreach($available_options as $avail)
printf('<option value="%s">%s</option>', $avail, $avail);
echo '</optgroup>';
}
echo '</select>';
This will create a select that renders like this in Safari (I selected red and large):

How to access mysql result set data with a foreach loop

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']";
}

Categories