I am trying to expand on some working code, and not sure how to do it.
Basicly the information can be under either information or some othertitle.
but i dont care for this split, i just want to do a foreach for all of them together.
Basicly i currently run a for each loop like this:
foreach ($info_array['information'] as $item) {... do something }
Would it be possible to somehow say, For each info_array 'information' & 'othertitle' as $item?
array is structured like:
information
random number
price
amount
total
random number
price
amount
total
othertitle
random number
price
amount
total
random number
price
amount
total
i tried this, but that didnt work:
foreach ($item_array['information'] as $item and $item_array['othertitle'] as $item)
The first idea that comes in mind is just use two loops - first one iterates over $item_array['information'], second one - over $item_array['othertitle']. Something like this:
foreach ($item_array['information'] as $item) {
echo $item['key1'] . ' -> ' . $item['key2'];
}
foreach ($item_array['othertitle'] as $item) {
echo $item['key1'] . ' -> ' . $item['key2'];
}
But, if you do the same output for each element of each array, you can do this:
$keys = ['information', 'othertitle'];
foreach ($keys as $key) {
echo 'Key is ' . $key . '<br />';
foreach ($item_array[$key] as $item) {
echo $item['key1'] . ' -> ' . $item['key2'];
}
}
And even it the output for arrays is different - you can solve it in this way:
$keys = ['information', 'othertitle'];
foreach ($keys as $key) {
echo 'Key is ' . $key . '<br />';
foreach ($item_array[$key] as $item) {
if ('information' === $key) {
echo 'Info: ' . $item['key1'] . ' -> ' . $item['key2'];
} else {
echo 'Ttile: ' . $item['key1'] . ' and ' . $item['key2'];
}
}
}
And if you have to iterate over all subarrays of $item_array, the solution is the same as in #AbraCadaver answer:
foreach ($item_array as $key => $items) {
echo 'Key is ' . $key . '<br />';
foreach ($items as $item) {
if ('information' === $key) {
echo 'Info: ' . $item['key1'] . ' -> ' . $item['key2'];
} else {
echo 'Ttile: ' . $item['key1'] . ' and ' . $item['key2'];
}
}
}
Since you know the indexes you could array_merge or use +:
foreach ($item_array['information'] + $item_array['othertitle'] as $item) {
// do something
}
Otherwise you need two loops:
foreach ($item_array as $array) {
foreach($array as $item) {
// do something
}
}
Related
I have very little experience with PHP, but I'm taking a class that has PHP review exercises. One of them is to create a function that uses a loop to return all values of an array except the first value in an unordered list. I'm assuming there's a way to do this using a foreach loop but cannot figure out how. This is what I had but I feel like I am far off:
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
$favColor = $array['favColor'];
$favMovie = $array['favMovie'];
$favBook = $array['favBook'];
$favWeb = $array['favWeb'];
echo '<h1>' . $myName . '</h1>';
function my_function() {
foreach($array == $myName){
echo '<ul>'
. '<li>' . $favColor . '</li>'
. '<li>' . $favMovie . '</li>'
. '<li>' . $favBook . '</li>'
. '<li>' . $favWeb . '</li>'
. '</ul>';
}
}
my_function();
?>
The correct syntax of foreach is
foreach (array_expression as $key => $value)
instead of
foreach($array == $myName){
function that uses a loop to return all values of an array except the
first value
I'm not sure, what exactly you mean by except the first value. If you are trying to remove first element from the array. Then you could have used array_shift
If you are supposed to use loop then
$count = 0;
foreach ($array as $key => $value)
{
if ($count!=0)
{
// your code
}
$count++;
}
Change the code to following
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
echo '<h1>' . $myName . '</h1>';
function my_function($array)
{
$count = 0;
echo "<ul>";
foreach($array as $key => $value)
{
if($key != "myName")
{
echo "<li>".$value."</li>";
}
}
echo "</ul>";
}
my_function($array);
i dont speak english but i will try get it.
My problems is on foreach ($json->mods->$k as $name) { because i'm getting duplicates <li>:
Heres the example:
<ul id="1">
<LI><B>BR:</B>
<LI><B>BR:</B>
<LI><B>BR:</B> Asterixmod, Explanado, Modquack</li>
<br>
<LI><B>DE:</B> Sweetphoenix</li>
<br>
<LI><B>E2:</B>
<LI><B>E2:</B> Irishcow, Welshnutter</li>
</ul>
CODE:
<?php
echo '<ul id="1">';
$link = '.json';
$f = file_get_contents($link);
$json = json_decode($f);
if (empty($json)) {
echo '<li id="ere"><B>ERROR</B></li>';
} else {
foreach ($json as $key => $val) {
foreach ($val as $k => $v) {
foreach ($json->mods->$k as $name) {
echo strtoupper('<li><b>' . $k . ':</b> ');
}
echo(implode(', ', $json->mods->$k));
echo '</li><br>';
}
}
echo '</ul>';
}
Hope anyone help me, ty.
The reason you're getting this error is because inside your foreach ($json->mods->$k as $name) you are opening an <li>, however, you're not closing it until after that loop. This means that eg. BR will have 3 opening tags and one closing tag.
Furthermore, you can get the output you want with just 1 loop:
foreach ($json->mods as $key => $val) {
echo '<li><b>' . strtoupper($key) . ':</b> ';
echo implode(', ', $val);
echo '</li><br>';
}
or you could even make the echo one line:
foreach ($json->mods as $key => $val) {
echo '<li><b>' . strtoupper($key) . ':</b> ' . implode(', ', $val) . '</li><br>';
}
Hope this helps!
I'm trying to modify a function that I've been using to dynamically populate <select> element to use arrays from a database. The original function used hard-coded arrays to populate the elements, and pre-selected the option which matched the db value.
The revised function creates the element, but it's only adding the first value from the db. How can I modify it so that it will loop through all the values that should be added to the <select> element?
PHP Function and Query
<?php
function printSelectOptions($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . $value . '</option>';
}
}
try {
$stmt = $conn->prepare("SELECT * FROM student");
$stmt->execute();
}catch(PDOException $e) {
echo $e->getMessage();
}
$row = $stmt->fetch();
?>
Populate Select Element
<select name="fname">
<?php
echo printSelectOptions(array($row['fname']));
?>
</select>
The Original Function & Code for Populating an Element
function printSelectOptions($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
}
}
<select name="fname">
<?php
$options = array("John"=>"John", "Mary"=>"Mary", "Elizabeth"=>"Elizabeth");
$selected = $row['fname'];
echo printSelectOptions($options, $selected);
?>
</select>
Since you have only fetched a single row via fetch(), only a single value is getting passed into your function printSelectOptions(). Instead, get all rows via fetchAll()
and modify your function to receive the full array, plus a string which is the column name (array key) you want to print from.
// All rows into $rows...
$rows = $stmt->fetchAll();
// Make the function accept the full 2D array, and
// a string key which is the field name to list out:
function printSelectOptions($dataArray, $currentSelection, $fieldname) {
// String to hold output
$output = '';
foreach ($dataArray as $key => $value) {
// Rather than echo here, accumulate each option into the $output string
// Use the $fieldname as a key to $value which is now an array...
$output .= '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
}
return $output;
}
Then call the function as:
echo printSelectOptions($rows, $currentSelection, 'fname');
The way it is right now, the option's value attribute is populated by the array key, which would be numbered from zero. That's similar to your original array version, but it might be more useful to specify another column name like id as the key column.
// This one also takes a $valuename to use in place of $key...
function printSelectOptions($dataArray, $currentSelection, $valuename, $fieldname) {
// String to hold output
$output = '';
foreach ($dataArray as $key => $value) {
// Rather than echo here, accumulate each option into the $output string
// Use the $fieldname as a key to $value which is now an array...
$output .= '<option ' . (($value[$valuename] == $currentSelection)) . ' value="' . $value[$valuename] . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
}
return $output;
}
And would be called as:
echo printSelectOptions($rows, $currentSelection, 'id', 'fname');
I have this array similar to this:
$suppliers = array(
'Utility Warehouse' => array('Gas' => array(0,0), 'Electricty' => array(0,0)),
'British Gas' => array('Gas' => array(93,124), 'Electricty' => array(93,124)),
'Eon' => array('Gas' => array(93,124), 'Electricty' => array(93,124))
);
How can display the information as follows
Utility Warehouse
Gas: 0-0 Electricity 0-0
British Gas
Gas: 93-134 Electricity: 93-134
Eon
Gas: 93-124 Electricity: 93-134
You can see how the displayed data corresponds to the data in the array. I've tried this:
foreach($suppliers as $a){
echo $a[0];
}
But this does nothing. CONFUSED!
<?php
foreach($suppliers as $supplier => $category) {
echo $supplier . '<br />';
foreach($category as $cat_name => $values_arr) {
echo $cat_name . ': ' . implode('-', $values_arr) . '<br /><br />';
}
}
?>
you can try:
foreach($suppliers as $name => $value) {
echo $name . "<br />";
foreach($value as $a => $price) {
echo $a .': '. $price[0].'-'.$price[1];
}
echo "<br /><br />";
}
The code to achieve what you want would be following, but i suggest you brush up on your PHP skills a bit more, as this is a trivial task.
foreach($suppliers as $name => $data){
echo $name . '<br/>';
foreach($data as $utility => $value){
echo $utility . ': ' . $value[0] . '-' . $value[1] . ' ';
}
echo '<br/><br/>';
}
Same answer as everyone else (I'm too slow). Here's a working example: http://codepad.org/PDPEjAGJ
Also, everyone who answered this question, me included, is guilty of spoonfeeding. Ahh well, the things I'll do for points! :p
Here is a simple recursive function one can use. I found it and modified it for presentation purposes. The original source is in the comments.
function print_a($array, $level=0){
# source: https://thisinterestsme.com/php-using-recursion-print-values-multidimensional-array/
foreach($array as $key => $value){
# If $value is an array.
if(is_array($value)){
echo str_repeat("-", $level). "<br>{$key}<br>\r\n";
# We need to loop through it.
print_a($value, $level + 1);
} else{
# It is not an array, so print it out.
echo str_repeat("-", $level) . "{$key}: {$value}<br>\r\n";
}
}
} # END FUNCTION print_a
foreach ($data['tests'] as $testname => $tests) {
echo "<h1>Extraction $testname Tests</h1>\n";
$function = $testfunctions[$testname];
echo "<ul>";
foreach ($tests as $test) {
echo "<li>" . $test['description'] . ' ... ';
$extracted = $extractor->$function($test['text']);
if ($test['expected'] == $extracted) {
echo " <span style='color: green'>passed.</span></li>";
} else {
echo " <span style='color: red'>failed.</span>";
echo "<pre>Original: " . htmlspecialchars($test['text']) . "\nExpected: " . print_r($test['expected'], true) . "\nActual : " . print_r($extracted, true) . "</pre>";
}
echo "</li>";
}
echo "</ul>";}
I keep getting the error:
Warning: Invalid argument supplied for
foreach() in
C:\xampp\htdocs\test\runtests.php on
line 49
p.s. the beginning of the code is line 49, so the probelm starts with the foreach statment.
Whenever i see that, it tends to mean that the thing i'm trying to iterate through isn't an array.
Check $data['tests'] (and each inner $tests) to make sure it's not null/unset/empty, and that it's something iterable like an array. Also keep in mind that older versions of PHP (before 5.0?) don't do iterable objects very well.
One of the elements in $data["tests"] is probably not an array.
Add this before the foreach:
if (is_array($tests))
foreach ($tests as $test) {...