Trouble displaying variable in foreach loop using multidimentional array - php

I'm able to display id and tags in the foreach loop no problem. But I'm having trouble showing title and height. I'm not sure how to call them into the foreach loop.
I can call them in the while loop so I know that they are working.
$persons = array();
$tags = array();
while( ($row = mysqli_fetch_array( $rs, MYSQLI_ASSOC)))
{
if(!isset( $persons[$row['id']]))
{
$persons[$row['id']]['title'] = $row['title'];
$persons[$row['id']]['height'] = $row['height'];
$persons[ $row['id'] ] = array( 'id' => $row['id'], 'tag' => $row['tag']);
$tags[ $row['id'] ] = array();
}
$tags[ $row['id'] ][] = $row['tag'];
}
foreach( $persons as $pid => $p)
{
echo 'id: # ' . $p['id'] ;
echo 'title: ' . $p['title'];
echo 'height: ' . $p['height'];
echo '' . implode( ', ', $tags[ $p['id'] ]) . '';
echo '<br /><br />';
}

You're overwriting $persons[ $row['id'] ] when you set the tags, so you lost the other data.

Related

i want add multiple product using php session

I want to print both
<?php
//in file A
$_SESSION['cart']['prices'] = array('1000');
$_SESSION['cart']['services'] = array('game');
//In File B
$_SESSION['cart']['prices'] = array('2000');
$_SESSION['cart']['services'] = array('game2');
//in file C
foreach ($_SESSION['cart']['services'] as $key => $service) {
echo $service . ' = ' . $_SESSION['cart']['prices'][$key] . '<br />';
}
?>
Better use this :
$_SESSION['cart']['prices'][] = array('1000');
$_SESSION['cart']['services'][] = array('game');
//In File B
$_SESSION['cart']['prices'][] = array('2000');
$_SESSION['cart']['services'][] = array('game2');
According to the current data foreach loop will execute two times. It will print Array as $service is array array('1000') and array('2000') same as for $_SESSION['cart']['prices'][$key]
foreach ($_SESSION['cart']['services'] as $key => $service) {
echo $service . ' = ' . $_SESSION['cart']['prices'][$key] . '<br />';
}
Try this :
$array1 = array('1000','2000');
$array2 = array('game1','game2');
foreach($array1 as $index=>$key)
{
$_SESSION['cart']['prices'][] = $key;
$_SESSION['cart']['services'][] = $array2[$index];
}
foreach ($_SESSION['cart']['services'] as $key => $service) {
echo $service . ' = ' . $_SESSION['cart']['prices'][$key] . '<br />';
}

PHP check array into array or multidimensional array

i want to create HTML element with PHP functions. in this section i have select function to create select tag. for values i want to check if array is simple my function create simple select otherwise create optgroup for options.
my create select method :
$tag->select( 'myselect',
array(
'0'=>'please choose','1'=>'111','2'=>'222','3'=>'333'
) ,
'2',
array(
'class'=>'myClass','style'=>'width:10%;'
)
);
other use:
$tag->select( 'myselect',
array( 'one'=>
array('0'=>'please choose','1'=>'111','2'=>'222','3'=>'333'),
'two'=>
array('0'=>'please choose','1'=>'111','2'=>'222','3'=>'333')
) ,
'2',
array(
'class'=>'myClass','style'=>'width:10%;'
)
) ;
now in below function i want to check if array into array exist function must be create select group;
public function select( $name, $values, $default='0', $attributs=[]){
$options = [];
$selected = '';
echo count($values);
if ( count($values) == 1){
foreach ($values as $value => $title) {
if ( $value === $default ) $selected="selected='selected'";
$options[] = "<option value = '$value' $selected>" . $title . '</option>'.PHP_EOL ;
$selected = '';
}
}
else{
foreach ($values as $key => $value) {
$options[] = "<optgroup label='$key'>";
foreach ($value as $selectValue => $title) {
$options[] = "<option value = '$selectValue'>" . $title . '</option>'.PHP_EOL ;
}
$options[] = "</optgroup>";
}
}
$selectTag = '<select ' . $this->setAttribute($attributs) . '>'.PHP_EOL;
return $selectTag . implode($options, ' ') . '</select>';
}
this function is not correct. how to resolve that? thanks.
Try this (hopefully helps you)
public function select( $name, $values, $default='0', $attributs=[]){
$options = [];
$selected = '';
echo count($values);
foreach ($values as $key => $value) {
if (!is_array($value)) {
if ( $key === $default ) $selected="selected='selected'";
$options[] = "<option value = '$key' $selected>" . $value . '</option>'.PHP_EOL ;
$selected = '';
}
else {
$options[] = "<optgroup label='$key'>";
foreach ($value as $selectValue => $title) {
$options[] = "<option value = '$selectValue'>" . $title . '</option>'.PHP_EOL ;
}
$options[] = "</optgroup>";
}
}
$selectTag = '<select ' . $this->setAttribute($attributs) . '>'.PHP_EOL;
return $selectTag . implode($options, ' ') . '</select>';
}

Add to an array at the end of a loop

What I want at the end of this code is an array which keeps adding to give and array with all $id in one array.
At the moment the code does 15 in the array, then gets overwritten by the next 15 items. I want to be able to an array at the end of the code which has 30 items in the array.
My code below:
$idArray = array();
do {
$html = file_get_html($url);
parseItems($html, $dbh);
sleep_flush($chunks=1); // ADJUST LATER
}
while (!empty($html->find('span[class=load-more-message]', 0)));
$html->clear();
unset($html);
// -------------------------------------------------
function parseItems($html, $dbh) {
foreach($html->find('div.product-stamp-inner') as $content) {
$detail['itemid'] = filter_var($content->find('a.product-title-link', 0)->href, FILTER_SANITIZE_NUMBER_FLOAT);
$id = $detail['itemid'];
$idArray[] = $id; //Counting and adding items to an array
$detail['title'] = $content->find('span.title', 0)->plaintext;
$description = $detail['title'];
if (!tableExists($dbh, $id, $detail)) {
echo $id . " > " . $description . "> Table does not exist >";
createTable($dbh, $id, $description);
insertData($dbh, $id, $detail);
echo "<br>";
} else {
echo $id . " > " . $description . "> Table already exists >";
checkData($dbh, $id, $detail);
echo "<br>";
}
}
print_r($idArray);
}
This is, because you redefine your $idArray here:
$idArray = array();
You could either make your $idArray global/member variable of the class.. or you can pass the parameter by reference:
$idArray = array();
do {
$html = file_get_html($url);
parseItems($html, $dbh, $idArray);
sleep_flush($chunks=1); // ADJUST LATER
}
while (!empty($html->find('span[class=load-more-message]', 0)));
$html->clear();
unset($html);
// -------------------------------------------------
function parseItems($html, $dbh, &$idArray) {
foreach($html->find('div.product-stamp-inner') as $content) {
$detail['itemid'] = filter_var($content->find('a.product-title-link', 0)->href, FILTER_SANITIZE_NUMBER_FLOAT);
$id = $detail['itemid'];
$idArray[] = $id; //Counting and adding items to an array
$detail['title'] = $content->find('span.title', 0)->plaintext;
$description = $detail['title'];
if (!tableExists($dbh, $id, $detail)) {
echo $id . " > " . $description . "> Table does not exist >";
createTable($dbh, $id, $description);
insertData($dbh, $id, $detail);
echo "<br>";
} else {
echo $id . " > " . $description . "> Table already exists >";
checkData($dbh, $id, $detail);
echo "<br>";
}
}
print_r($idArray);
}

Looping through array objects to output

I have sent $data['items'] to my view which has created an array full of objects which I can echo with a foreach loop.
foreach($items as $row)
{
echo $row->NAME . " - " . $row->COLOUR . "<br>";
}
what I want to do is echo them to the browser in groups with the name of the colour as a header tag then start the loop for that colour. I'm just not sure what type of loop to do or should I have a loop within a loop?
BLUE
-item 1
-item 3
RED
-item 2
-item 4
-item 5
$list = array();
foreach($items as $row)
{
$list[$row->COLOUR][] = $row->NAME;
}
$header = null;
foreach($list as $item)
{
if($header != $item->COLOUR)
{
echo '<h3>' . $item->COLOUR . '</h3>';
$header = $item->COLOUR;
}
echo '- ' . $item->NAME . '<br />';
}
You probably want an interim two-dimensional array:
$tmp = array();
foreach($items as $row)
{
// this code groups all items by color
$name = $row->NAME;
if( !isset ($tmp[ $name ] ) ) $tmp[ $name ] = array();
$tmp[ $name ][] = $row->COLOUR;
}
foreach( $tmp as $color => $items )
{
// colors are now keys to the temp array
echo $color;
// these are all of the items grouped under the current color
foreach( $items as $item )
{
// output the item.
echo "<br /> - $item";
}
echo "<br />";
}

Two arrays in foreach loop

I want to generate a selectbox using two arrays, one containing the country codes and another containing the country names.
This is an example:
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
foreach( $codes as $code and $names as $name ) {
echo '<option value="' . $code . '">' . $name . '</option>';
}
?>
This method didn't work for me. Any suggestions?
foreach( $codes as $code and $names as $name ) { }
That is not valid.
You probably want something like this...
foreach( $codes as $index => $code ) {
echo '<option value="' . $code . '">' . $names[$index] . '</option>';
}
Alternatively, it'd be much easier to make the codes the key of your $names array...
$names = array(
'tn' => 'Tunisia',
'us' => 'United States',
...
);
foreach operates on only one array at a time.
The way your array is structured, you can array_combine() them into an array of key-value pairs then foreach that single array:
foreach (array_combine($codes, $names) as $code => $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}
Or as seen in the other answers, you can hardcode an associative array instead.
Use array_combine() to fuse the arrays together and iterate over the result.
$countries = array_combine($codes, $names);
array_map seems good for this too
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
array_map(function ($code, $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}, $codes, $names);
Other benefits are:
If one array is shorter than the other, the callback receive null values to fill in the gap.
You can use more than 2 arrays to iterate through.
Use an associative array:
$code_names = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France');
foreach($code_names as $code => $name) {
//...
}
I believe that using an associative array is the most sensible approach as opposed to using array_combine() because once you have an associative array, you can simply use array_keys() or array_values() to get exactly the same array you had before.
This worked for me:
$codes = array('tn', 'us', 'fr');
$names = array('Tunisia', 'United States', 'France');
foreach($codes as $key => $value) {
echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "<br>";
}
Your code like this is incorrect as foreach only for single array:
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
foreach( $codes as $code and $names as $name ) {
echo '<option value="' . $code . '">' . $name . '</option>';
}
?>
Alternative, Change to this:
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
$count = 0;
foreach($codes as $code) {
echo '<option value="' . $code . '">' . $names[count] . '</option>';
$count++;
}
?>
Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
becomes:
$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');
You can use array_merge to combine two arrays and then iterate over them.
$array1 = array("foo" => "bar");
$array2 = array("hello" => "world");
$both_arrays = array_merge((array)$array1, (array)$array2);
print_r($both_arrays);
All fully tested
3 ways to create a dynamic dropdown from an array.
This will create a dropdown menu from an array and automatically assign its respective value.
Method #1 (Normal Array)
<?php
$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');
echo '<select name="countries">';
foreach($names AS $let=>$word){
echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
?>
Method #2 (Normal Array)
<select name="countries">
<?php
$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>
</select>
Method #3 (Associative Array)
<?php
$my_array = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France'
);
echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>
Walk it out...
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
PHP 5.3+
array_walk($codes, function ($code,$key) use ($names) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
});
Before PHP 5.3
array_walk($codes, function ($code,$key,$names){
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
},$names);
or combine
array_walk(array_combine($codes,$names), function ($name,$code){
echo '<option value="' . $code . '">' . $name . '</option>';
})
in select
array_walk(array_combine($codes,$names), function ($name,$code){
#$opts = '<option value="' . $code . '">' . $name . '</option>';
})
echo "<select>$opts</select>";
demo
<?php
$codes = array ('tn','us','fr');
$names = array ('Tunisia','United States','France');
echo '<table>';
foreach(array_keys($codes) as $i) {
echo '<tr><td>';
echo ($i + 1);
echo '</td><td>';
echo $codes[$i];
echo '</td><td>';
echo $names[$i];
echo '</td></tr>';
}
echo '</table>';
?>
foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a while loop:
while(($code = each($codes)) && ($name = each($names))) {
echo '<option value="' . $code['value'] . '">' . $name['value'] . '</option>';
}
each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.
Instead of foreach loop, try this (only when your arrays have same length).
$number = COUNT($_POST["codes "]);//count how many arrays available
if($number > 0)
{
for($i=0; $i<$number; $i++)//loop thru each arrays
{
$codes =$_POST['codes'][$i];
$names =$_POST['names'][$i];
//ur code in here
}
}
array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an attempt to update products quantities in a shopping cart.
I think that you can do something like:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
foreach ($codes as $key => $code) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
}
It should also work for associative arrays.
I think the simplest way is just to use the for loop this way:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
for($i = 0; $i < sizeof($codes); $i++){
echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}
if(isset($_POST['doors'])=== true){
$doors = $_POST['doors'];
}else{$doors = 0;}
if(isset($_POST['windows'])=== true){
$windows = $_POST['windows'];
}else{$windows = 0;}
foreach($doors as $a => $b){
Now you can use $a for each array....
$doors[$a]
$windows[$a]
....
}
I solved a problem like yours by this way:
foreach(array_keys($idarr) as $i) {
echo "Student ID: ".$idarr[$i]."<br />";
echo "Present: ".$presentarr[$i]."<br />";
echo "Reason: ".$reasonarr[$i]."<br />";
echo "Mark: ".$markarr[$i]."<br />";
}
You should try this for the putting 2 array in singlr foreach loop
Suppose i have 2 Array
1.$item_nm
2.$item_qty
`<?php $i=1; ?>
<table><tr><td>Sr.No</td> <td>item_nm</td> <td>item_qty</td> </tr>
#foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)
<tr>
<td> $i++ </td>
<td> $item_nm </td>
<td> $item_qty </td>
</tr></table>
#endforeach `
Few arrays can also be iterated like this:
foreach($array1 as $key=>$val){ // Loop though one array
$val2 = $array2[$key]; // Get the values from the other arrays
$val3 = $array3[$key];
$result[] = array( //Save result in third array
'id' => $val,
'quant' => $val2,
'name' => $val3,
);
}
This will only work if the both array have same count.I try in laravel, for inserting both array in mysql db
$answer = {"0":"0","1":"1","2":"0","3":"0","4":"1"};
$reason_id = {"0":"17","1":"19","2":"15","3":"19","4":"18"};
$k= (array)json_decode($answer);
$x =(array)json_decode($reason_id);
$number = COUNT(json_decode($reason_id, true));
if($number > 0)
{
for($i=0; $i<$number; $i++)
{
$val = new ModelName();
$val->reason_id = $x[$i];
$val->answer =$k[$i];
$val->save();
}
}
En laravel Livewire
return view('you_name_view', compact('data','data2'));
#foreach ($data as $index => $data )
<li>
<span>{{$data}}</span>
<span>{{$data2[$index]}}</span>
</li>
#endforeach
it works for me
$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}

Categories