PHP Merging Arrays and presenting output in dot points - php

The output of the following code gives: MilkYoghurtCheese AppleOrangeBanana. Being new to php, I am having difficulty producing these elements as dot points in a list, rather than combined words in a sentence.
Is there a way to put these into dot points?
<?php
$newArray =array();
$DairyArray=array();
$FruitArray=array();
$DairyArray= array(
'1' => 'Milk',
'2' => 'Yoghurt',
'3' => 'Cheese',
);
$FruitArray = array(
'9' => 'Apple'
'10' => 'Orange',
'11' => 'Banana',
if ($_POST['Dessert'] == 'Yes') //This represents the condition that a checkbox is
checked
{
$newArray = array_merge($DairyArray, $FruitArray);
foreach ($newArray as $key => $value)
{
echo $value >;
}
}
What I am trying to achieve as output:
• Milk
• Yogurt
• Cheese
• Apple
• Orange
• Banana
Any help would be greatly appreciated, and I will try to see if I can answer some of your questions too.
Thanks
Andrew

The echo command only outputs the raw data in the variable (in your case array). You want to pimp it out a bit for a nice display like this:
$newArray = array_merge($DairyArray, $FruitArray);
echo "<ul>";
foreach ($newArray as $key => $value)
{
echo "<li>" . $value . "</li>";
}
echo "</ul>";
Keep in mind that HTML by default requires explicit instructions on how to display something, and omits line breaks, more than one space at a time and many other things. When we deal with data in variables, for the most part, they are generally the raw data without any formatting. You will always need to make it formatted nicely for your web pages - or get used to horrible text only pages :)

Use implode instead of foreach
<?php
$DairyArray= array(
'1' => 'Milk',
'2' => 'Yoghurt',
'3' => 'Cheese'
);
$FruitArray = array(
'9' => 'Apple',
'10' => 'Orange',
'11' => 'Banana'
);
$newArray = array_merge($DairyArray, $FruitArray);
echo ".".implode(".",$newArray);
?>
Also if you want to use bullet then you can use
<?php
echo "<ul><li>";
echo implode("</li><li>",$newArray);
echo "</li></ul>";
?>
<style>
ul li { float:left; margin-right:25px; }
</style>

Related

Change languages in PHP echo or print

Please help me to solve this issue. I'm not sure is it possible or not! I need a small tricky solution.
<?php include_once"system/hijri_calendar.php";
echo (new hijri\datetime()) -> format ('_j');
?>
Above code gives me an output of integer (1...30) in English.
Now, After echo, I want to change this English language to other languages.
Example:
Say Above code gives me an output 1
I want to change this output (1) to other languages (১)
If I get you right you are trying to get the value from one array based on the value and key from another array. You can use array_search() to find the key from array based on value
<?php
$en = array(1,2,3,4,5,6,7,8,9,0);
$bn = array('১','২','৩','৪','৫','৬','৭','৮','৯','০');
var_dump(array_search(5, $en)); // gives the key 4 from $en where value is 5
// array keys strart with 0
// so you can do
var_dump($bn[array_search(5, $en)]); // gives ৬
PHPFiddle to play with
Quick and dirty:
function __($number, $lang)
{
if ($lang == 'en') {
return $number;
}
$translate = array();
$translate['bn'] = array(
'1' => '১',
'2' => '২',
'3' => '৩',
'4' => '৪',
'5' => '৫',
'6' => '৬',
'7' => '৭',
'8' => '৮',
'9' => '৯',
'0' => '০'
);
$translate['th'] = array(
'1' => '๑',
'2' => '๒',
'3' => '๓',
'4' => '๔',
'5' => '๕',
'6' => '๖',
'7' => '๗',
'8' => '๘',
'9' => '๙',
'0' => '๐'
);
$digits = str_split($number,1);
$return_this = '';
foreach($digits as $digit){
$return_this .= $translate[$lang][$digit];
}
return $return_this;
}
echo __('905','bn');
Break down, if the lang is en you get what you give, if bn or th, it'll break the number apart and rebuild it using the requested array.
This is basically how I do I18n except the arrays for each language are in their own files.
I've changed the arrays slightly to simplify things. If the array is in the order of the digits (so I've moved the 0 element to position 0 in the array) you can use...
$bn = array('০','১','২','৩','৪','৫','৬','৭','৮','৯');
$in = "18";
$out = "";
foreach ( str_split($in) as $ch ) {
$out .= $bn[$ch];
}
echo $out;

PHP MySQL Assign variables to array data

I have the following:
$sql="SELECT course_status, COUNT(course_name) FROM courses GROUP BY course_status";
Then a while loop to store the data:
$menu[] = array(
'sum_status' => $row['COUNT(course_name)'],
'course_status' => $row['course_status']
);
I can print_r($menu) with all data.
How can I assign the keys and values to different variables like:
$status_0 = $key[0] <br>
$count_0 = $value[0] <br>
$status_1 = $key[1] <br>
$count_1 = $value[1] <br>
and so on...?
Thank you!
A little more info, perhaps pasting the code, would be helpful. If I understand it correctly, you could just change your query to:
$sql="SELECT course_status as 'status', COUNT(course_name) as 'count' FROM courses GROUP BY course_status";
Then a simple foreach loop will give you the right display.
I am not entirely understanding your question. But iterating through an array of arrays is a simple as:
<?php
$items = [
[
'foo' => 'Hello',
'bar' => 23
],
[
'foo' => 'Earth',
'bar' => 47
]
];
foreach($items as $item) {
echo $item['foo'];
echo $item['bar'];
}
Output:
Hello23Earth47
Further, rather than assigning to individual variables, you can access an individual item's value by targeting the appropriate key:
echo $items[1]['foo'];
Output:
Earth
To parse the array item in a string, wrap with curlies:
echo "{$items[0]['foo']} Dolly";
Output:
Hello Dolly

PHP Sorting array of arrays based on another user-defined array

Hoping I am not opening a duplicate question but I didn't see this type of question being asked or the answers I saw didn't seem to work with my dataset (but I'm very new at this).
I am hoping to sort the following data set (array of arrays) based on another array of strings.
The code is running and it is only running the generateHtml function for strings that exist in the $ntbooks array which is by design. What I need to solve is how to perform a custom sort using the $ntbooks as the order. Right now, as the code runs and the content is parsed from content.php, the order the data is populated into the menu is the order in which it is seen (top to bottom of array)--I would like to sort the data so that Matthew is written out, then Mark, then Luke, etc.
This is a sample of my data but there are over 250 arrays (contentids) in it and I would like to avoid restructuring or reorganizing my dataset. When all is said and done, the generateHTML should start with matthew, mark, luke, and work its way through the list.
Thank you in advance for your help!
Dynamically Generated HTML Menu (menu.php):
include('content.php');
$main = array();
foreach($articles as $article)
{
foreach(explode("; ", $article["verse"]) as $verseData)
{
$verse = explode(" ", $verseData);
$book = $verse[0];
$verse = explode(":", $verse[1]);
$chapter = $verse[0];
if(empty($main[$book]))
$main[$book] = array();
if(empty($main[$book][$chapter]))
$main[$book][$chapter] = array();
if(empty($main[$book][$chapter][$verse[1]]))
$main[$book][$chapter][$verse[1]] = array();
$main[$book][$chapter][$verse[1]] = array
(
"full" => $article["full"]
);
}
}
$ntbooks = array("Matthew", "Mark", "Luke", "John", "Acts", "Romans", "1Corinthians", "2Corinthians", "Galatians", "Ephesians", "Philippians", "Colossians", "1Thessalonians", "2Thessalonians", "1Timothy", "2Timothy", "Titus", "Philemon", "Hebrews", "James", "1Peter", "2Peter", "1John", "2John", "3John", "Jude", "Revelation");
foreach($main as $book => $data)
{
if (in_array($book, $ntbooks)) {
generateHtml($book, $data);
}
}
function generateHtml($book, $data)
{
echo "<!-- ". $book ." -->\n";
echo "<div class=\"submenu\">\n";
echo "". $book ."\n";
echo "<!-- Level 2 menu -->\n";
echo "<div>\n";
echo "<div>\n";
foreach($data as $chapter => $verses)
{
echo "<div class=\"submenu\">\n";
echo "Chapter ". $chapter ."\n";
echo "<!-- Level 3 menu -->\n";
echo "<div>\n";
echo "<div>\n";
foreach($verses as $verse => $value)
{
echo "Verse ". $verse ."\n";
}
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
}
}
PHP Array of Arrays (content.php):
$articles = array(
array(
'contentid' => '0',
'full' => 'Item1 by Artist Name1 (Matthew 4)',
'verse' => 'Matthew 4:18-22',
'commentary' => ''),
array(
'contentid' => '1',
'full' => 'Item2 by Artist Name2 (Luke 15)',
'verse' => 'Luke 15:11-14; Luke 15:20-21',
'commentary' => ''),
array(
'contentid' => '2',
'full' => 'Item3 by Artist Name3 (John 3)',
'verse' => 'John 3:1-9',
'commentary' => ''),
array(
'contentid' => '3',
'full' => 'Item4 by Artist Name4 (John 8)',
'verse' => 'John 8:1-15A',
'commentary' => ''),
array(
'contentid' => '4',
'full' => 'Item5 by Artist Name5 (Matthew 27; Luke 23; John 19)',
'verse' => 'Matthew 27:20-23A; Luke 23:20-25A; John 19:2-3A',
'commentary' => 'Here '));
You need to sort using a custom comparison function, where the values being compared will be the keys from the reference array that correspond to the values from the data array.
So if:
$order = ['Matthew', 'Mark', 'Luke'];
and your data array's verse is guaranteed to be one of the above values (in your example this is not true!) then you could do it with
$comparison = function($a, $b) use ($order) {
return array_search($a['verse'], $order) - array_search($b['verse'], $order);
};
usort($data, $comparison);
However, it's not as simple in your case because verse is not as convenient as that. You will need to somehow extract the value of interest out of it, an exercise which I will not attempt to solve because there are too many unknowns (e.g. how is 'Matthew 27:20-23A; Luke 23:20-25A; John 19:2-3A' supposed to be sorted?).
Use usort.
From: http://php.net/manual/en/function.usort.php
bool usort ( array &$array , callable $value_compare_func ).
Basically, you call usort with the array you would like to sort and a function that would indicate the sort order (compare the two objects and determines which one is "greater").
Since the book is in the verse object, you can do something like this:
function sortCompare($obj1, $obj2)
{
$book1 = explode($obj1['verse'])[0];
$book2 = explode($obj2['verse'])[0];
return indexOf($book1, $ntbooks) - indexOf($book2, $ntbooks);
}
At which point you can call
usort($articles, "sortCompare");.
The sortCompare function above might need tweaking but it's a good start.

Multiple Arrays foreach statement

I am working on my first PHP Layout from my existing HTML. I am running in to trouble. I hope stackoverflow can help
I have 3 arrays
$parent = array('1' => 'parent1' , 'parent2' , 'parent3' , 'parent4' , );
$child = array('1' => 'child1' , 'child2' , 'child3' , 'child4' , );
$content = array('1' => 'content1' , 'content2' , 'content3' , 'content4' , );
I am trying to use them to make a repeating list which will include {$parent}, {$child}, and {$content} like the following..
<?php
echo "<h1 id='js-overview' class='page-header'>$parent</h1>"
echo "<h3 id='js-fotopia'>$child</h3>"
echo "<p>$content</p>"
?>
but i need to run this for each of my variables. How do I write the statement? also how can I set it up so that the child and child content are also repeating. like in the pic
See the pic to understand my layout that i need to keep repeating as long as there are variables filled out... Please ask questions if i am not making since rather than skipping... I need php guidance.
I think your structure is a bit off. Instead of 3 arrays, why not combine them into one? It's a little unclear how the parent/child/content relationship you have is setup, but here's a shot:
$arr = array(
'parent1' => array(
'child1' => array(
'content' => 'This is your content for child 1',
),
'child2' => array(
'content' => 'This is your content for child 2',
),
),
'parent2' => array(
'child1' => array(
'content' => 'This is your content for child 1 inside of parent 2',
)
),
);
Then you can just foreach over the array, and foreach over the children:
foreach($arr as $parent) {
foreach($parent as $childName => $child) {
echo $child['content'];
}
}
You can add more keys into the children array if you need more structure to your content.
Perhaps something like this?
for($i=1; $i<=count($parent); $i++){
echo "<h1 id='js-overview' class='page-header'>$parent[$i]</h1>"
echo "<h3 id='js-fotopia'>$child[$i]</h3>"
echo "<p>$content[$i]</p>"
}
Alternatively you could use a foreach and assuming the keys line up like this syntax
foreach (array_expression as $key => $value)
statement
Alternatively to that you could construct 1 2D array that stores the parent, child and content all in 1 row.

PHP - 2D Arrays - Looping through array keys and retrieving their values?

I have an array that outputs like this:
1 =>
array
'quantity' => string '2' (length=1)
'total' => string '187.90' (length=6)
2 =>
array
'quantity' => string '2' (length=1)
'total' => string '2,349.90' (length=8)
I would like to loop through each array keys and retrieve the set of 3 values relating to them, something like this (which doesnt work):
foreach( $orderItems as $obj=>$quantity=>$total)
{
echo $obj;
echo $quantity;
echo $total;
}
Would someone be able to give some advice on how I would accomplish this, or even a better way for me to be going about this task. Any information relating to this, including links to tutorials that may cover this, would be greatly appreciated. Thanks!!
foreach( $orderItems as $key => $obj)
{
echo $key;
echo $obj['quantity'];
echo $obj['total'];
}
Using the above.
You need to read the docs on forEach() a little more, since your syntax and understanding of it is somewhat incorrect.
$arr = array(
array('foo' => 'bar', 'foo2', 'bar2'),
array('foo' => 'bar', 'foo2', 'bar2'),
);
foreach($arr as $sub_array) {
echo $sub_array['foo'];
echo $sub_array['bar'];
}
forEach() iteratively passes each key of the array to a variable - in the above case, $sub_array (a suitable name, since your array contains sub-arrays). So within the loop body, it's that you need to interrogate.

Categories