So, I am sending a query based on a POST input that takes in numerous options, and want to print out one table PER selected option. I implode the array and it is correctly displaying the data, however it's all lumped up into one table where I need it separated. This is an example of my array now:
Array
(
[Selected Option 1] => Array
(
[Item 1] => Array
(
[Item 1 Data 1] => etc
[Item 1 Data 2] => etc
[Item 1 Data 3] => etc
)
)
And basically I need the table to be like Table 1: Selected Option 1 displaying all items and their data, followed by Table 2: Selected Option 2, and so on.
How is something like this done? When I do the foreach loop, it successfully prints out the header to each table (Selected Option 1, etc) but Im not sure how to filter it so only the correct data is printed instead of the ENTIRE array.
Thanks!
So far, this is what my foreach looks like
foreach ($selected_opt as $port=> $item) {
foreach ($item as $itemx => $data){
$var1= $data['1'];
$var2= $data['2'];
$var3= $data['3'];
You can use foreach inside foreach
let say your array is = $data
<?php
foreach ($data as $selectedOption => $items) {
echo $selectedOption . "<br>";
foreach ($items as $itemName => $itemData) {
echo $itemName . "<br>";
foreach ($itemData as $item) {
echo $item . "<br>";
}
}
}
?>
If you want to filter
echo $data["Selected Option 1"]["Item 1"]
Related
So I'm trying to find the details for a particular item in one array from a different array:
foreach($json_items['result']['items'] as $item)
{
foreach($items_all['items_game']['items'] as $schemaItem)
{
echo $Schema[$item['defindex']];
if($item['defindex'] == $Schema[$item['defindex']])
{
echo "works";
echo $schemaItem['name'].'<br />';
break;
} else {
//echo "not";
}
}
}
defindex is a unqiue ID for the item, Schema is a database type array of item info
but Schema is designed like this:
[1] => Array
(
[name] => Anti-Mage's Glaive
[prefab] => default_item
So 1 here would be the defindex for this item in the Schema array
What can I do so can compare them and get out the info such as name and prefab for the item? Thanks.
Is this inside of a loop through the array? If so, you could try:
foreach ($item as $key => $value){
// Do compare here, $key would be the array index $value the value.
}
You could access the array in $Schema
$item = $Schema[$item['defindex']];
$item_name = $item['name'];
$item_prefab = $item['prefab'];
I have the following array:
print_r($all_projects);
--------------------------------
Array (
[0] => Array (
[pro_id] => 7
[0] => 7
)
[1] => Array (
[pro_id] => 20
[0] => 20
)
)
How do I grab each pro_id in a foreach loop?
I can find quite a bit information online on how to create an array, and how to grab the key and value from an array. But I have difficulty grabbing the value of a key in an array, in an array.
I currently have this for each:
foreach ($all_projects as $project => $project_id){
echo $project_id;
}
Which in turn returns the following:
Array
Array
This makes sense to me, but how do I go deeper in the array?
foreach($all_projects as $project) {
echo $project['pro_id'];
}
try:
foreach ($all_projects as $project => $project_id){
echo $project_id['pro_id'];
}
or even cleaner to read :
foreach ($all_projects as $project){
echo $project['pro_id'];
}
foreach($all_projects as $KEY => $VALUE) {
echo "KEY: $KEY - PRO_ID: {$VALUE['pro_id']}";
}
In your case, you'd want:
foreach ($all_projects as $project_id => $project) {
echo $project_id . " = " . $project['pro_id'];
}
Now with PHP5.5, you have an easy way to do it:
foreach ($all_projects as list($id))
echo $id;
And the old way:
foreach ($all_projects as $project)
echo $project['pro_id'];
Hope it'll help you!
If we're looping through the $all_projects with foreach loop this way,
foreach ($all_projects as $key => $project) {
echo($key);
}
then $key will actually be 0, 1, etc., not 7 or 20 -- as you might intended this to be -- and $project will be the content of the project.
In your case, I presume that the "project id" you desired are stored inside the "project" array itself, so as other suggested, you should write something like
foreach($all_projects as $project) { // omitting the $key part since you don't need it
echo($project['pro_id']);
}
this will print the actual "project id", which is the pro_id that you want.
If you were to improve this code, you might want to restructure your $all_projects this way
$all_projects = array();
$all_project[7] = $some_project; // your first project with id 7
$all_project[20] = $some_other_project; // your second project with id 20
then you will be able to use your original code to loop through:
foreach($all_projects as $project_id => $project) {
echo($project_id);
}
with $project_id be 7, 20, etc., and $project be the content of your project.
Hope this answers your question!
I am trying to solve the following problem:
Note I am new to programming and PHP and working through SAMS PHP, MySQL and Apache (Julie C. Meloni).
There is an exercise where a multidimensional array has to be created. The outer array is an associative array listing the genres of movies. The genre arrays list movies of that genre. You are then asked to print out a list of genres with the list of films associated with that genre.
My code:
<?php
$genres = array(
'Science Fiction' => array('Star Trek', 'Star Wars', 'Alien'),
'Drama' => array('Les Amant de Pont Neuf', 'War & Peace', 'Bridehead Revisited'),
'Crime' => array('Heat', 'Pulp Fiction', 'Messerine')
);
$gKeys = array_keys($genres);
foreach ($gKeys as $genre) {
print $genre."<br/>";
}
?>
This works and prints out:
Science Fiction
Drama
Crime
Here's where I am running into a wall. When I try adding another foreach loop after
print $genre;
no results appear in the browser (except results of first loop). I have tried everything. For example:
starting by using the array_value() function applied to $genre and then try a foreach on the array returned.
In the textbook there is also a while (list($x) = ($y)) mechanism mentioned.
I thoroughly re-read the array chapter and have looked elsewhere to no avail.
perhaps I have structured the multidimensional array incorrectly? Do the second dimensional arrays need to be associative arrays also for consistency?
Your array is structured correctly. You're taking wrong array (array of just the keys) and adding another foreach loop after print $genre; hence it is not working.
No, it is not required for second dimensional arrays to be associative arrays as well.
<?php
$genres = array(
'Science Fiction' => array('Star Trek', 'Star Wars', 'Alien'),
'Drama' => array('Les Amant de Pont Neuf', 'War & Peace', 'Bridehead Revisited'),
'Crime' => array('Heat', 'Pulp Fiction', 'Messerine')
);
foreach ($genres as $genre => $movies)
{
print $genre . " - <br/>";
foreach ($movies as $movie)
{
print $movie . "<br/>";
}
print "</br>";
}
?>
Wait! Why are you doing:
$gKeys = array_keys($genres);
This just gives you a single array of keys.
Do your first loop on $genres, then inside:
foreach ($genre as $key=>$subgenre)
{
//do stuff here
}
foreach ($genres as $genrekey => $genrevalue) {
print $genrekey."<br/>";
foreach ($genrevalue as $value) {
print $value."<br/>";
}
}
function multiarray_keys($ar) {
foreach($ar as $k => $v) {
$keys[] = $k;
if (is_array($ar[$k]))
$keys = array_merge($keys, multiarray_keys($ar[$k]));
}
return $keys;
}
$gKeys = multiarray_keys($genres);
echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";
Your outer array is an associative array with genres as keys.
To print out movies of that genre (the subarrays), use another foreach as follows:
print "<ul>";
foreach ($genres as $genre => $movies) {
print "<li>".$genre."<ul>";
foreach ($movies as $movie) {
print "<li>".$movie."</li>";
}
print "</ul></li>";
}
print "</ul>";
If you need this for seeing what data goes in an array for debugging purposes you could use PHPs var_export(), var_dump(), print_r() only to make sure the data is getting populated as you want it to. Otherwise if you want to show it in production you could do some like this:
foreach($multiDimentinalArray as $key => $value):
if(is_array($value)):
foreach($value as $k => $val):
print " $key.$k => $val";
else:
print "$key => $value";
endif;
endforeach;
I have an array which is of the following form in PHP-
Array(
0 =>
array (
0 => 'var1=\'some var1\'',
1 => 'var2=\'some_var2\'',
2 => 'var3=\'some_var3\'',
))
and I want it to appear as-
array (
0 => 'var1=\'some var1\'',
1 => 'var2=\'some_var2\'',
2 => 'var3=\'some_var3\'',
)
So how to do it?
Have you tried...
$inner_array = $outer_array[0];
var_dump($inner_array);
...?
Read here in the manual about more details to arrays in php.
Multidimensional arrays generally work as shown below
$shop = array( array("rose", 1.25 , 15),
array("daisy", 0.75 , 25),
array("orchid", 1.15 , 7)
);
echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2];
The syntax of foreach construct is as follow:
foreach ($array_expression as $value) {
statement
}
foreach ($array_expression as $key => $value) {
statement
}
The first form loops over the array given by $array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one so that on the next loop, the next element is accessed.
The second form does the same thing, except that the current element’s key will be assigned to the variable $key on each loop.
The foreach syntax above is also similar to the following while construct:
while (list(, $value) = each($array_expression)) {
statement
}
while (list($key, $value) = each($array_expression)) {
statement
}
Even for loop can be used to process and loop through all elements of arrays with the following syntax:
$count = sizeof($arr_expression);
for ($i = 0; $i < $count; $i++) {
$value = $arr_express[$i];
statement
}
for ($i = 0, $item = ''; false != ($value = $arr_expression[$i]); $i++) {
statement
}
Nested loop of “foreach” can also be used to access multidimensional arrays. Here’s an example array and the way to access its value data. For example:
foreach ($array_expression as $arr_value) {
foreach ($array_value as $value) {
statement
}
}
Here’s an example code to access an array:
$contents = array(
"website_1" => array("name" => "StackOverFlow",
"url" => "http://www.stackoverflow.com",
"favorite" => "yes"),
"website_2" => array("name" => "Tip and Trick",
"url" => "http://www.tipandtrick.net",
"favorite" => "yes")
);
To retrieve the data, programmers can specify the keys that lead to the value directly with the following syntax, which will print the “My Digital Life”.
echo $contents['website_1']['name'];
However, the syntax above becomes unpractical when dealing with large arrays, or when the name of the keys and values changed dynamically. In this case, the “foreach” function can be used to access an array recursively.
foreach ($contests as $key => $list) {
echo "Website No.: " . $key . "\n";
echo "Name: " . $list['name'] . "\n";
echo "URL: " . $list['url'] . "\n";
}
The output will be:
Website No.: website_1
Name: StackOverFlow
URL: http://www.stackoverflow.com/
Website No.: website_2
Name: Tip and Trick
URL: http://www.tipandtrick.net/
I have a multi-select box for country selection. I want to select any countries which are associated, meaning an array I get from the database.
Here's the code I have:
<?php
foreach($countries as $country){
if(!empty($offer_countries)){
foreach($offer_countries as $key => $offer_country){
if(isset($offer_country['country_id']) && ($offer_country['country_id'] == $country['id'])){
echo '<option value="'.$country['id'].'" selected>'.$country['name'].'</option>';
}else{
echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
}
}
}else{
echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
}
}
?>
The $offer_countries array, looks like this:
Array
(
[0] => Array
(
[country_id] => 1
)
[1] => Array
(
[country_id] => 2
)
[2] => Array
(
[country_id] => 3
)
)
I'm looping all countries to display them, then I have a nested foreach to see if the country is already set, if so, make the option box selected.
The problem with this is that let's say I have 3 items selected, it'll display 3 of the same country, based on the number of items in the array. So if United States should be checked, it'll show it three times, with the last one checked.
Ok, sorry for the looong explanation, it's probably fairly self explanatory, but any help would be awesome!
This solved it:
<?php
foreach($countries as $country){
$i = 0;
if(!empty($offer_countries)){
foreach($offer_countries as $key => $offer_country){
if($offer_country['country_id'] == $country['id']){
echo '<option value="'.$country['id'].'" selected>'.$country['name'].'</option>';
$i = 1;
break;
}
}
if($i == 0){
echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
}
}else{
echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
}
}
?>
Your inner 'foreach' statement is going to output 'something' whether or not the value is set, and it does so based on the $country variable set up in the outer foreach loop.
So what happens is that you output on the outer 'foreach' loop once for each time it runs on the inner foreach loop.