How to display only Maths value in this code - php

Here i want display only Maths marks,i don't know how to do, i am trying but i am not able to display:-
<?php
$marks1=array(
array("Maths"=>80,"Physics"=>89,"Chemistry"=>79),
array("Maths"=>90,"Physics"=>78,"Chemistry"=>87),
array("Maths"=>78,"Physics"=>90,"Chemistry"=>79)
);
echo "<ul>";
for($r=0;$r<count($marks1);$r++)
{
echo "<li>";
foreach($marks1[$r] as $key=>$value)
{
echo $key." = ".$value." ";
}
echo "</li>";
echo "<br><br>";
}
echo "</ul>";
?>

Please prefer using foreach() only. And avoid things like echo "<ul>" etc.... Follow the below coding format...
<?php
$marks1 = array(
array("Maths" => 80, "Physics" => 89, "Chemistry" => 79),
array("Maths" => 90, "Physics" => 78, "Chemistry" => 87),
array("Maths" => 78, "Physics" => 90, "Chemistry" => 79)
);
?>
<ul>
<?php foreach($marks1 as $marks) { ?>
<li>
Maths = <?php echo $marks['Maths']; ?>
</li>
<?php } ?>
</ul>

I hope it's the shortest way to do so-
<?php
$marks1=array(
array("Maths"=>80,"Physics"=>89,"Chemistry"=>79),
array("Maths"=>90,"Physics"=>78,"Chemistry"=>87),
array("Maths"=>78,"Physics"=>90,"Chemistry"=>79)
);
foreach($marks1 as $mark){
echo "MATH = ".$mark['Maths']."<br>";
}
?>
Output :
MATH = 80
MATH = 90
MATH = 78

Related

I want to echo multi-dimensional array by using foreach loop

<?php
$StudScore = array(
"Mary" => array(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"Tom" => array(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"Jon" => array(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
foreach ($StudScore as $key => $value) {
echo "<li>$key</li>";
if (is_array($value)) {
echo "<ul>";
echoArray($value);
echo "</ul>";
} else {
echo "<ul><li>$value</li></ul>";
}
}
?>
Till now i have tried to print array but i am getting below error kindly help me out with this .
Output :
Mary
Fatal error: Call to undefined function echoArray()
i want it to be print as example:
Mary = physics:35,maths:30,chemistry:39
Tom = physics:30,maths:32,chemistry:29
Jon = physics:31,maths:22,chemistry:39
It has to be either echo var_dump($value); or echo print_r($value); if you want to print the WHOLE array. There is no function called echoArray() in PHP.
When you only want to print ONE key/value from the array, you also have to use echo $value;, since the keys/values are only strings.
See https://www.php.net/manual/en/function.var-dump.php and https://www.php.net/manual/en/function.print-r.php
<?php
foreach ($StudScore as $name => $value) {
echo $name." = ";
foreach ($value as $subject => $marks) {
echo $subject.":".$marks.",";
}
echo "<br/>";
}
?>
Finally i got my answer it give output like :
Mary = physics:35,maths:30,chemistry:39
Tom = physics:30,maths:32,chemistry:29
Jon = physics:31,maths:22,chemistry:39

resume foreachloop after incrementing php bootstrapp drop down menu

Question in short: i want to output array: 0, 1 , 2 then break, echo something , output 3,4,5 and keep this in a loop.
Hello everyone i am working on a dynamic php website with bootstrap 4 and php to practice the language. Unfortunately i am now stuck since i dont know how to create something that kindoff looks like an algorith. Allright enough talking and lets get down to the code:
nav.php file
<ul class="navbar-nav">
<li class='nav-item dropdown'>
<a class='nav-link dropdown-toggle' data-toggle='dropdown' datatarget='dropdown_target' href='#'>
<span class='caret'></span>Dropdown
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-menu" aria-labelledby="dropdown_target">
<!-- <a class="dropdown-item">Dropdown</a> -->
<?php
$i=0;
foreach ($dropItems as $item ) {
echo "<a class='dropdown-item' href=\"$item[slug]\">$item[title] </a>";
$i++;
if($i==1) break;
echo "<a class='dropdown-item'>Dropdown</a>";
}
?>
</div>
</li>
</li>
<?php
foreach ($navItems as $item ) {
echo "<li class='nav-item'> <a class='nav-link' href=\"$item[slug]\">$item[title]</a> </li>";
}
?>
</ul>
arrays.php
<?php
//Navigatie menu items
$navItems = array(
array(
"slug" => "index.php",
"title" => "home"
),
array(
"slug" => "contact.php",
"title" => "Contact"
),
array(
"slug" => "market.php",
"title" => "Marketplace"
),
);
$dropItems = array(
array(
"slug" => "#",
"title" => "Lps"
),
array(
"slug" => "#",
"title" => "Sps"
),
array(
"slug" => "market.php",
"title" => "Marketplace"
),
);
?>
You can use array_chunk to split the array in the chunks of three and foreach nested with echo "something";.
Can't see in your code where this echo of three is so I just made an example of how to do it.
$arr = range(1,12); //example array
$chunks = array_chunk($arr, 3);
Foreach($chunks as $chunk){
Foreach($chunk as $val){
Echo $val ." ";
}
Echo "\nsomething\n";
}
https://3v4l.org/0VlN0
Thanks to Andreas i got it working using his method
$chunks = array_chunk($dropItems, 2);
Foreach($chunks as $chunk){
Foreach($chunk as $item){
echo "<a class='dropdown-item' href=\"$item[slug]\">$item[title] </a>";
}
Echo "<div class='dropdown-divider'></div>";
}

PHP: Help in Retrieving and Echoing Multidimensional Array ID

I'm looking to display a list of available weapons of a game, based on items listed in an array. I'm able to display information suck as 'Attribute Values' and 'Price' perfectly via a foreach loop, however being a PHP newbie, I'm having a lot of trouble working out how to echo each item's ID, such as 'Short Sword', 'Middle Sword', 'Long Sword', etc. I thought I was getting close using key($sword)... but no dice. Here's what I'm working with:
<?php $item_swords = Array();
$item_swords["Short Sword"] = Array (
"Attribute Value" => 5,
"Price" => 100,
);
$item_swords["Middle Sword"] = Array (
"Attribute Value" => 8,
"Price" => 250,
);
$item_swords["Long Sword"] = Array (
"Attribute Value" => 12,
"Price" => 750,
); ?>
<?php foreach ($item_swords as $sword) { ?>
<li>
<img src="<?php echo $sword["Item Sprite"]; ?>">
<span><?php echo $sword; ?></span>
<div>ATT +<?php echo $sword["Attribute Value"]; ?></div>
<div><?php echo $sword["Price"]; ?>G</div>
</li>
<?php } ?>
If anyone could lend a hand and help demonstrate how best to echo an item's ID or a per item basis throughout my loop, then that would be very awesome indeed. Thank you for your time.
try with this code
use key attr in foreach loop
and echo $key value instead of array like $sword
<?php $item_swords = Array();
$item_swords["Short Sword"] = Array (
"Attribute Value" => 5,
"Price" => 100,
);
$item_swords["Middle Sword"] = Array (
"Attribute Value" => 8,
"Price" => 250,
);
$item_swords["Long Sword"] = Array (
"Attribute Value" => 12,
"Price" => 750,
); ?>
<?php foreach ($item_swords as $key=>$sword) { ?>
<li>
<img src="
<?php //echo $sword["Item Sprite"]; ?>">
<span><?php echo $key; ?></span>
<div>
ATT +
<?php echo $sword["Attribute Value"]; ?></div>
<div>
<?php echo $sword["Price"]; ?>G
</div>
</li>
<?php } ?>

How to create a HTML Table from a PHP array?

How do I create a HTML table from a PHP array? A table with heading as 'title', 'price', and 'number'.
$shop = array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 1.15, 7 ),
);
It would be better to just fetch the data into array like this:
<?php
$shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),
array("title"=>"daisy", "price"=>0.75 , "number"=>25),
array("title"=>"orchid", "price"=>1.15 , "number"=>7)
);
?>
And then do something like this, which should work well even when you add more columns to your table in the database later.
<?php if (count($shop) > 0): ?>
<table>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($shop as $row): array_map('htmlentities', $row); ?>
<tr>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
Here's mine:
<?php
function build_table($array){
// start table
$html = '<table>';
// header row
$html .= '<tr>';
foreach($array[0] as $key=>$value){
$html .= '<th>' . htmlspecialchars($key) . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . htmlspecialchars($value2) . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
$array = array(
array('first'=>'tom', 'last'=>'smith', 'email'=>'tom#example.org', 'company'=>'example ltd'),
array('first'=>'hugh', 'last'=>'blogs', 'email'=>'hugh#example.org', 'company'=>'example ltd'),
array('first'=>'steph', 'last'=>'brown', 'email'=>'steph#example.org', 'company'=>'example ltd')
);
echo build_table($array);
?>
<table>
<tr>
<td>title</td>
<td>price</td>
<td>number</td>
</tr>
<? foreach ($shop as $row) : ?>
<tr>
<td><? echo $row[0]; ?></td>
<td><? echo $row[1]; ?></td>
<td><? echo $row[2]; ?></td>
</tr>
<? endforeach; ?>
</table>
You can also use array_reduce
array_reduce — Iteratively reduce the array to a single value using a callback function
example:
$tbody = array_reduce($rows, function($a, $b){return $a.="<tr><td>".implode("</td><td>",$b)."</td></tr>";});
$thead = "<tr><th>" . implode("</th><th>", array_keys($rows[0])) . "</th></tr>";
echo "<table>\n$thead\n$tbody\n</table>";
This is one of de best, simplest and most efficient ways to do it.
You can convert arrays to tables with any number of columns or rows.
It takes the array keys as table header. No need of array_map.
function array_to_table($matriz)
{
echo "<table>";
// Table header
foreach ($matriz[0] as $clave=>$fila) {
echo "<th>".$clave."</th>";
}
// Table body
foreach ($matriz as $fila) {
echo "<tr>";
foreach ($fila as $elemento) {
echo "<td>".$elemento."</td>";
}
echo "</tr>";
}
echo "</table>";}
echo "<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>";
foreach($shop as $v){
echo "<tr>";
foreach($v as $vv){
echo "<td>{$vv}</td>";
}
echo "<tr>";
}
echo "</table>";
echo '<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>';
foreach($shop as $id => $item) {
echo '<tr><td>'.$item[0].'</td><td>'.$item[1].'</td><td>'.$item[2].'</td></tr>';
}
echo '</table>';
<table>
<thead>
<tr><th>title</th><th>price><th>number</th></tr>
</thead>
<tbody>
<?php
foreach ($shop as $row) {
echo '<tr>';
foreach ($row as $item) {
echo "<td>{$item}</td>";
}
echo '</tr>';
}
?>
</tbody>
</table>
Here is my answer.
function array2Html($array, $table = true)
{
$out = '';
foreach ($array as $key => $value) {
if (is_array($value)) {
if (!isset($tableHeader)) {
$tableHeader =
'<th>' .
implode('</th><th>', array_keys($value)) .
'</th>';
}
array_keys($value);
$out .= '<tr>';
$out .= array2Html($value, false);
$out .= '</tr>';
} else {
$out .= "<td>".htmlspecialchars($value)."</td>";
}
}
if ($table) {
return '<table>' . $tableHeader . $out . '</table>';
} else {
return $out;
}
}
However, your table headers have to be a part of the array, which is pretty common when it comes from a database. e.g.
$shop = array(
array(
'title' => 'rose',
'price' => 1.25,
'number' => 15,
),
array(
'title' => 'daisy',
'price' => 0.75,
'number' => 25,
),
array(
'title' => 'orchid',
'price' => 1.15,
'number' => 7,
),
);
print array2Html($shop);
Hope it helps ;)
Build two foreach loops and iterate through your array.
Print out the value and add HTML table tags around that.
You may use this function. To add table header you can setup a second parameter $myTableArrayHeader and do the same with the header information in front of the body:
function insertTable($myTableArrayBody) {
$x = 0;
$y = 0;
$seTableStr = '<table><tbody>';
while (isset($myTableArrayBody[$y][$x])) {
$seTableStr .= '<tr>';
while (isset($myTableArrayBody[$y][$x])) {
$seTableStr .= '<td>' . $myTableArrayBody[$y][$x] . '</td>';
$x++;
}
$seTableStr .= '</tr>';
$x = 0;
$y++;
}
$seTableStr .= '</tbody></table>';
return $seTableStr;
}
PHP code:
$multiarray = array (
array("name"=>"Argishti", "surname"=>"Yeghiazaryan"),
array("name"=>"Armen", "surname"=>"Mkhitaryan"),
array("name"=>"Arshak", "surname"=>"Aghabekyan"),
);
$count = 0;
foreach ($multiarray as $arrays){
$count++;
echo "<table>" ;
echo "<span>table $count</span>";
echo "<tr>";
foreach ($arrays as $names => $surnames){
echo "<th>$names</th>";
echo "<td>$surnames</td>";
}
echo "</tr>";
echo "</table>";
}
CSS:
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;``
}
I had a similar need, but my array could contain key/value or key/array or array of arrays, like this array:
$array = array(
"ni" => "00000000000000",
"situacaoCadastral" => array(
"codigo" => 2,
"data" => "0000-00-00",
"motivo" => "",
),
"naturezaJuridica" => array(
"codigo" => "0000",
"descricao" => "Lorem ipsum dolor sit amet, consectetur",
),
"dataAbertura" => "0000-00-00",
"cnaePrincipal" => array(
"codigo" => "0000000",
"descricao" => "Lorem ips",
),
"endereco" => array(
"tipoLogradouro" => "Lor",
"logradouro" => "Lorem i",
"numero" => "0000",
"complemento" => "",
"cep" => "00000000",
"bairro" => "Lorem ",
"municipio" => array(
"codigo" => "0000",
"descricao" => "Lorem ip",
),
),
"uf" => "MS",
"pais" => array(
"codigo" => "105",
"descricao" => "BRASIL",
),
"municipioJurisdicao" => array(
"codigo" => "0000000",
"descricao" => "DOURADOS",
),
"telefones" => array(
array(
'ddd' => '67',
'numero' => '00000000',
),
),
"correioEletronico" => "lorem#ipsum-dolor-sit.amet",
"capitalSocial" => 0,
"porte" => "00",
"situacaoEspecial" => "",
"dataSituacaoEspecial" => ""
);
The function I created to solve was:
function array_to_table($arr, $first=true, $sub_arr=false){
$width = ($sub_arr) ? 'width="100%"' : '' ;
$table = ($first) ? '<table align="center" '.$width.' bgcolor="#FFFFFF" border="1px solid">' : '';
$rows = array();
foreach ($arr as $key => $value):
$value_type = gettype($value);
switch ($value_type) {
case 'string':
$val = (in_array($value, array(""))) ? " " : $value;
$rows[] = "<tr><td><strong>{$key}</strong></td><td>{$val}</td></tr>";
break;
case 'integer':
$val = (in_array($value, array(""))) ? " " : $value;
$rows[] = "<tr><td><strong>{$key}</strong></td><td>{$value}</td></tr>";
break;
case 'array':
if (gettype($key) == "integer"):
$rows[] = array_to_table($value, false);
elseif(gettype($key) == "string"):
$rows[] = "<tr><td><strong>{$key}</strong></td><td>".
array_to_table($value, true, true) . "</td>";
endif;
break;
default:
# code...
break;
}
endforeach;
$ROWS = implode("\n", $rows);
$table .= ($first) ? $ROWS . '</table>' : $ROWS;
return $table;
}
echo array_to_table($array);
And the output is this
<?php
echo "<table>
<tr>
<th>title</th>
<th>price</th>
<th>number</th>
</tr>";
for ($i=0; $i<count($shop, 0); $i++)
{
echo '<tr>';
for ($j=0; $j<3; $j++)
{
echo '<td>'.$shop[$i][$j].'</td>';
}
echo '</tr>';
}
echo '</table>';
You can optimize it, but that should do.
You can use foreach to iterate the array $shop and get one of the arrays with each iteration to echo its values like this:
echo '<table>';
echo '<thead><tr><th>title</td><td>price</td><td>number</td></tr></thead>';
foreach ($shop as $item) {
echo '<tr>';
echo '<td>'.$item[0].'</td>';
echo '<td>'.$item[1].'</td>';
echo '<td>'.$item[2].'</td>';
echo '</tr>';
}
echo '</table>';
this will print 2-dimensional array as table.
First row will be header.
function array_to_table($table)
{
echo "<table>";
// Table header
foreach ($table[0] as $header) {
echo "<th>".$header."</th>";
}
// Table body
$body = array_slice( $table, 1, null, true);
foreach ($body as $row) {
echo "<tr>";
foreach ($row as $cell) {
echo "<td>".$cell."</td>";
}
echo "</tr>";
}
echo "</table>";
}
usage:
arrayOfArrays = array(
array('header1',"header2","header3"),
array('1.1','1.2','1.3'),
array('2.1','2.2','2.3'),
);
array_to_table($arrayOfArrays);
result:
<table><tbody><tr><th>header1</th><th>header2</th><th>header3/th><tr><td>1.1</td><td>1.2</td><td>1.3</td></tr><tr><td>2.1</td><td>2.2</td><td>2.3</td></tr><tr><td>3.1</td><td>3.2</td><td>3.3</td></tr></tbody></table>
Array into table.
Array into div.
JSON into table.
JSON into div.
All are nicely handle this class. Click here to get a class
How to use it?
Just get and object
$obj = new Arrayinto();
Create an array you want to convert
$obj->array_object = array("AAA" => "1111",
"BBB" => "2222",
"CCC" => array("CCC-1" => "123",
"CCC-2" => array("CCC-2222-A" => "CA2",
"CCC-2222=B" => "CB2"
)
)
);
If you want to convert Array into table. Call this.
$result = $obj->process_table();
If you want to convert Array into div. Call this.
$result = $obj->process_div();
Let suppose if you have a JSON
$obj->json_string = '{
"AAA":"11111",
"BBB":"22222",
"CCC":[
{
"CCC-1":"123"
},
{
"CCC-2":"456"
}
]
}
';
You can convert into table/div like this
$result = $obj->process_json('div');
OR
$result = $obj->process_json('table');
Here is the more generic version of #GhostInTheSecureShell 's answer.
<?php
function build_tabular_format($items)
{
$html = '';
$items_chunk_array = array_chunk($items, 4);
foreach ($items_chunk_array as $items_single_chunk)
{
$html .= '<div class="flex-container">';
foreach ($items_single_chunk as $item)
{
$html .= '<div class="column-3">';
$html .= $item['fields']['id'];
$html .= '</div>';
}
$html .= '</div>';
}
return $html;
}
$items = array(
array(
'fields' => array(
'id' => '1',
) ,
) ,
array(
'fields' => array(
'id' => '2',
) ,
) ,
array(
'fields' => array(
'id' => '3',
) ,
) ,
array(
'fields' => array(
'id' => '4',
) ,
) ,
array(
'fields' => array(
'id' => '5',
) ,
) ,
array(
'fields' => array(
'id' => '6',
) ,
) ,
array(
'fields' => array(
'id' => '7',
) ,
) ,
array(
'fields' => array(
'id' => '8',
) ,
) ,
);
echo build_tabular_format($items);
?>
The output will be like:
<div class="flex-container">
<div class="column-3">1</div>
<div class="column-3">2</div>
<div class="column-3">3</div>
<div class="column-3">4</div>
</div>
<div class="flex-container">
<div class="column-3">5</div>
<div class="column-3">6</div>
<div class="column-3">7</div>
<div class="column-3">8</div>
</div>

PHP Arrays, displaying fruits like 1.apple 2.banana, etc

I have some array:
array
0 => string 'Apple'
1 => string 'banana'
2 => string 'Nanas'
3 => string 'Grape'
What is the best way to display
1. Apple
2. banana
3. Nanas
4. Grape
Any Ideas?
If the output you are after is HTML, then an ordered list makes sense:
<ol>
<?php foreach($fruits as $fruit) { ?>
<li><?php echo $fruit; ?></li>
<?php } ?>
</ol>
How about this?
foreach($fruits as $index => $fruit) {
echo ($index+1).". ".$fruit."\n";
}
If HTML
<ol>
<?php
foreach ($fruits as $fruit) {
echo "<li>", $fruit;
}
?>
</ol>

Categories