I am trying to do a website (don't ask what it is) and I need help.
I have created this page called meallist.php :
<?php
/* Ingredients List */
$meatlist = array(tavuketi => "Tavuk Eti",
baliketi => "Balık Eti");
$vegelist = array(domates => "Domates",
patates => "Patates",
salatalik => "Salatalık");
/* The Meals - dun dun duuuunnnnnn */
$yemekaralist = array(mangaldatavuk => array(
name => "Mangalda Tavuk",
ing1 => tavuketi),
mangaldapatateslitavuk => array(
name => "Mangalda Patatesli Tavuk",
ing1 => tavuketi,
ing2 => patates),
mangaldabalik => array(
name => "Mangalda Balık",
ing1 => baliketi),
firindapatateslibalik => array(
name => "Fırında Patatesli Balık",
ing1 => baliketi,
ing2 => patates));
?>
You get the idea. I made a foreach loop on index.php that creates a select:
<div id="etler">
<select multiple="multiple" name="selectMeal[]" size="4" data-max-length="30">
<?php
foreach($meatlist as $id => $name)
{
print "<option value=\"" . $id . "\">" . $name . "</option>";
}
?>
</select>
</div>
<div id="sebze">
<select multiple="multiple" name="selectMeal[]" size="4" data-max-length="30">
<?php
foreach($vegelist as $id1 => $name1)
{
print "<option value=\"" . $id1 . "\">" . $name1 . "</option>";
}
?>
</select>
</div>
And it posts the selectMeal[] and gets it into $search in searchmeal.php. The thing I want is, I want it to search the $yemekaralist in meallist.php and check if ing1 (and ing2 if available) if it matches with the selectMeal[] array, and print name => "something" if available. How can I do that?
Best regards,
mission712
Can you change the structure of $yemekaralist?
It would simplify your algorithm if you change the structure for something like this:
$yemekaralist = array(
item1 => array(
'name' => 'item1_name',
'ingredients' => array('tavuketi', 'patates'),
),
item2 => array(
'name' => 'item2_name',
'ingredients' => array('tavuketi', 'patates'),
),
And then go like this:
foreach ($yemekaralist as $item) {
foreach ($item['ingredients'] as $ingredient) {
foreach ($selectMeal as $selectedMeal) {
if ($selectedMeal == $ingredient) {
echo $item['name'];
}
}
}
}
Related
can you give me idea how to implement this idea for "dynamic" html table.
I have an array
$arr = array(
array(
'label' => 'First name',
'data' => array(
array('fname' => 'John'),
array('fname' => 'Ralph'),
),
),
array(
'label' => 'Last name',
'data' => array(
array('lname' => 'Doe'),
array('lname' => 'Loren'),
),
),
array(
'label' => 'Description',
'data' => array(
array('description' => 'Something bout John'),
array('description' => 'Something about Ralph'),
),
),
);
Now from the keys 'label' im creating the table columns
---------------------------------------
|First Name | Last Name | Description |
---------------------------------------
The problem is how to put 'fname' keys in the first column, 'lname' in the second and 'description' in the third.
With this part of code im trying to put the data in all columns
private function tableBody()
{
$data = $this->data;
$table = '<tbody>';
foreach($data as $key => $value){
foreach($value['data'] as $k => $v){
$table .= '<tr>';
foreach($v as $col => $name){
$table .= '<td>' . $name . '</td>';
}
$table .= '</tr>';
}
}
$table .= '</tbody>';
return $table;
}
Also my idea is not to hard code array keys for multiple usage(except label and data).
First I would remap the data to process it in loops.
$labels = [];
$rows = [];
foreach($arr as $column) {
$label = $column['label'];
$labels[] = $label;
foreach($column['data'] as $key => $value) {
$rows[$label][] = $value;
}
}
Now print out the labels with the headline.
echo "<table>\n";
echo "<tr>";
foreach($labels as $label) echo "<th>{$label}</th>";
echo "</tr>\n";
Iterate through the rows and create the HTML.
$labelCount = count($labels);
$rowCount = count($rows[$labels[0]]);
while($rowCount) {
echo "<tr>";
for ($i = 0; $i < $labelCount; $i++) {
$current = array_shift($rows[$labels[$i]]);
$value = reset($current);
echo "<td>{$value}</td>";
}
echo "</tr>\n";
$rowCount--;
}
echo "</table>\n";
This gives a table like below
<table>
<tr><th>First name</th><th>Last name</th><th>Description</th></tr>
<tr><td>John</td><td>Doe</td><td>Something bout John</td></tr>
<tr><td>Ralph</td><td>Loren</td><td>Something about Ralph</td></tr>
</table>
You need to manipulate the initial array to reduce it to something more manageable. You could brute force your way like so:
function reduce($data) {
$ret = [];
foreach ($data as $d1) {
// column header could have been fetched here
foreach ($d1 as $k2 => $d2) {
// keeping track of what label we need
$key = '';
// keeping the values together
$child = [];
// discarding non arrays
if (is_array($d2)) {
foreach ($d2 as $d3) {
// identifier fetch from this level
foreach ($d3 as $k4 => $d4) {
$key = $k4;
$child[] = $d4;
}
}
}
// assigning back to the main array only if we have something
if (!empty($child)) {
$ret[$key] = $child;
}
}
}
return $ret;
}
That will return the following:
Array
(
[fname] => Array
(
[0] => John
[1] => Ralph
)
[lname] => Array
(
[0] => Doe
[1] => Loren
)
[description] => Array
(
[0] => Something bout John
[1] => Something about Ralph
)
)
despite my efforts I wasn't able to find a suitable solution. Here is the problem:
All the data comes from a form with text fields named name[], gender[], and age[].
print_r($_POST) looks like:
[name] => Array ([2] => Adam [6] => Suzy )
[gender] => Array ( [2] => male [6] => female )
[age] => Array ( [2] => 30 [6] => 25 )
I am trying to iterate it like this:
foreach ($array as $value)
{
echo $value['name'].$value['gender'].$value['age']."<br>";
}
The result should look like this:
Adam - male - 30
Suzy - female - 25
You are close - but the syntax for creating arrays is slightly different.
$array = array (
array('name' => 'Adam', 'gender' => 'male', 'age' => 30),
array('name' => 'Suzy', 'gender' => 'female', 'age' => 25),
);
foreach ($array as $value)
{
echo $value['name'].$value['gender'].$value['age']."<br>";
}
You've got two options - you could create an array of two items; each has three details about a single person. That's what I did and it suits the loop you've shown.
Or you can have three parallel arrays - one with two names, one with two genders and one with two ages.
That second way would look more like:
$array = array(
'name' => array('Adam','Suzy'),
'gender' => array('male','female'),
'age' => array(30,25)
);
But it would be harder to get the output you want from that.
$array2 = array(
'name' => array('Adam','Suzy'),
'gender' => array('male','female'),
'age' => array(30,25)
);
for($i=0;$i<count($array2['name']);$i++){
echo $array2['name'][$i].$array2['gender'][$i].$array2['age'][$i].'<br/>';
}
Each of the arrays in $_POST have the same set of keys:
$_POST = array(
'name' => array(2 => 'Adam', 6 => 'Suzy'),
'gender' => array(2 => 'male', 6 => 'female'),
'age' => array(2 => '30', 6 => '25')
)
You can iterate one of the inner arrays, and use its key to access the corresponding values in the other arrays.
foreach ($_POST['name'] as $key => $name) {
echo $name . $_POST['gender'][$key] . $_POST['age'][$key] . "<br>";
}
foreach ($array as $id=>$value)
{
echo $value . $gender[$id] . $age[$id] . "<br>";
}
First of all I've modified the array structure that you posted on your question because it is not valid for in php. Then If I don't misunderstood you requirements then you've this array structure and you want to archive this-
<?php
$array = array (
'name'=>array('Adam', 'Suzy'),
'gender'=>array('male', 'female'),
'age'=>array(30, 25)
);
$i=0;
foreach ($array as $key=>$value)
{
if($i==2)break;
echo $array['name'][$i]."-".$array['gender'][$i] ."-". $array['age'][$i] ."<br>";
$i++;
}
?>
OR
<?php
$array = array (
'name'=>array('Adam', 'Suzy'),
'gender'=>array('male', 'female'),
'age'=>array(30, 25)
);
foreach ($array['name'] as $index=>$name)
{
echo $name."-".$array['gender'][$index] ."-". $array['age'][$index] ."\n";
}
?>
Program Output:
Adam-male-30
Suzy-female-25
DEMO: https://eval.in/1039966
#Being Sunny
Veeeery close to that sir I'v used back in 2003. Here is the working solution:
<?
echo "<pre>";
print_r($_POST);
echo "</pre>";
foreach ($_POST['name'] as $key => $name) {
echo "NAME=".$_POST['name'][$key]."gender=" . $_POST['gender'][$key] . "AGE=".$_POST['age'][$key] . "<br>";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
</head>
<body>
WOKSING SOLUTION:
<code>echo "<pre>";
print_r($_POST);
echo "</pre>";
foreach ($_POST['name'] as $key => $name) {
echo "NAME=".$_POST['nemae'][$key]."gender=" . $_POST['gender'][$key] . "AGE=".$_POST['age'][$key] . "<br>";
}
</code>
<form method="post">
<input type="text" name="name[]" />
<input type="text" name="gender[]"/>
<input type="text" name="age[]"/>
<br />
<input type="text" name="name[]" />
<input type="text" name="gender[]"/>
<input type="text" name="age[]"/>
<input type="submit" />
</form>
</body>
</html>
I have a multi-dimensional array as follows:
Array
(
[lists] => Array
(
[0] => Array
(
[id] => 23ybdwhdwbed
[name] => TEST
(
[1] => Array
(
[id] => e223edsewed
[name] => TEST 2
(
)
)
I want to access the ID & name variables using a foreach loop.
I'm using this:
$x = 0;
foreach($lists as $list){
$listId = $list[$x]['id'];
$listName = $list[$x]['name'];
echo"$x | $listId $listName <br />";
$x++;
}
For some strange reason, I can only get the value of the first $listId & $name, not the second $listId or $name.
What am I doing wrong here?
You're assuming that you still need to provide the key for each child element. This is not the case.
try
foreach($lists as $list){
$listId = $list['id'];
$listName = $list['name'];
$listId $listName <br />";
}
the foreach() will iterate over them in turn.
if you do need the index number, do this instead.
foreach($lists as $x => $list){
where $x is the index.
The array you posted is wrong because it's missing closing ), so correct that (I think that is TYPO mistake)
After that you need to do it like below:-
foreach($lists['lists'] as $key=> $list){
$listId = $list['id'];
$listName = $list['name'];
echo "$key | $listId $listName <br />";
}
Output:-https://eval.in/846464
Or an one-liner code:-
foreach($lists['lists'] as $key=> $list){
echo "$key | ".$list['id']." ".$list['name']." <br />";
}
Output:-https://eval.in/846465
Your foreach iterates the first, not the second level of your multi dimensional array.
Since the first level only holds the lists array as one and only element the loop only executes once.
Pass the lists key to the foreach instead like so:
$x = 0;
foreach($lists['lists'] as $list) {
echo "$x | " . $list['id'] . " " . $list['name'] . "<br />";
++$x;
}
Also note how in here I reference the list elements by name to make it easier to read.
I think those numerical indexed will just confuse you so try this instead:
$my_array = array(array("id" => "23ybdwhdwbed", "name" => "TEST"), array("id" => "e223edsewed", "name" => "TEST 2"));
To access the values: use:
foreach($my_array as $my_data){
echo "ID:" . $my_data["id"];
echo "<br>";
echo "NAME:" .$my_data["name"];
echo "<br><br>";
}
you just need to do:
foreach($lists['list'] as $listKey=>$listValue){
$listId = $listValue['id'];
$listName = $listValue['name'];
echo"$listKey | $listId : $listName <br />";
}
Try this, I fixed your array structure to work, this is also dynamic so it does not matter how many array you have 0 -> above
$array = array(
'lists' => array(
'0' => array(
'id' => '23ybdwhdwbed',
'name' => 'TEST 1'
),
'1' => array(
'id' => 'e223edsewed',
'name' => 'TEST 2'
)
)
);
foreach ($array as $key => $value) {
for($ctr = 0; $ctr < count($value); $ctr++){
echo 'ID: ' . $value[$ctr]['id'] . '<br>';
echo 'Name: : ' . $value[$ctr]['name'] . '<br><br>';
}
}
I need to create to dependant dropDownLists with yii. Thus, I create a view and an action in controller like this :
The view
<?php
echo "<div class='row'>";
echo $form->labelEx($model, 'id_structure');
echo $form->dropDownList($model, 'id_structure', GxHtml::listDataEx(StructureInformation::model()->findAllAttributes()),
array('ajax' => array('type' => 'POST',
'url' => CController::createUrl('InfoComplementAAjouter/fillTypeList'),
'update' => '#typeDonnee',
'data' => array('id_structure' => 'js:this.value'))
));
echo $form->error($model, 'id_structure');
echo '</div>';
echo "<div class='row'>";
echo $form->labelEx($model, 'type');
echo $form->dropDownList($model, 'type', array(), array('prompt' => 'Sélectionner', 'id' => 'typeDonnee'));
echo $form->error($model, 'type');
echo '<div>';
?>
Now the action in the Controller InfoComplementAAjouterController :
public function actionFillTypeList(){
$id_struct = $_POST['InfoComplementAAjouter']['id_structure']; //I get the selected value
$taille = StructureInformation::model()->find('id = ' . (int)$id_struct)->taille; //and then pass it to the StructureInformation model to obtain the attribute taille
//I create two arrays which content will be the options of my dropDownList.
$un = array('text'=> 'Texte', 'radio' => 'Bouton radio', 'dropDownList' => 'Liste déroulante');
$plusieurs = array( 'checkboxlist' => 'Choix multiple',);
//If $taille == 1, I display the contents of $un; if $taille > 1, the content of $plusieurs will be displayed.
if($taille == 1){
foreach ($un AS $value => $name){
$opt = array();
$opt['value'] = $value;
echo CHtml::tag('option', $opt, CHtml::encode($name), true);
}
}
if($taille > 1){
foreach ($plusieurs AS $value => $name){
$opt = array();
$opt['value'] = $value;
echo CHtml::tag('option', $opt, CHtml::encode($name), true);
}
}
die;
}
I remark that the action is not executed. I can not understand why.
Can somebody help me to fix the problem ?
I just saw a typo:
'upedate' => '#typeDonnee',
should be 'update'
try with fixing it first
Edit:
you have more small errors/typos
echo $form->dropDownList($model, 'id_structure', GxHtml::listDataEx(StructureInformation::model()->findAllAttributes(),
array('ajax' => array('type' => 'POST',
'url' => CController::createUrl('InfoComplementAAjouter/fillTypeList'),
'update' => '#typeDonnee',
'data' => array('id_structure' => 'js:this.value'))
));
here you need to close parentheses
=====================================================
StructureInformation::model()->findAllAttributes()
there is no findAllAttributes() method in CActiveRecord
maybe you wanted to use findAllByAttributes(), but then you would want to pass some attributes. If this is your custom method then you should explain how it works, or paste a code
Edit 2:
$_POST['InfoComplementAAjouter']['id_structure']
Try to access post like this:
$_POST['id_structure']
I think you send post in that structure
It's not that easy for me to duplicate your situation, so I'm kinda shooting in the dark
Hello i just finish a code where i get like 50 variables... all of them with int values..
I have the variables as separete values, just for this example I will set the variables with the result, BUT the result came from other evaluations and stuff that its fine, cause im already echoing a verified result.
$one = 13
$two = 35
$three = 46
The "item1" appears <?PHP echo $one; ?> times<br />
The "item2" appears <?PHP echo $two; ?> times<br />
The "item3" appears <?PHP echo $three; ?> times<br />
This is fine but,, How can i order the results, in ASC way or DSC , to build a order by...
Thanks so much
This far this is working great
$naturales = array(
$uno => "n1",
$dos => "n2",
$tres => "n3",
$cuatro => "n4",
$cinco => "n5",
$seis => "n6",
$siete => "n7",
$ocho => "n8",
$nueve => "n9",
$diez => "n10",
$once => "n11",
$doce => "n12",
$trece => "n13",
$catorce => "n14",
$quince => "n15",
$dieciseis => "n16",
$diecisiete => "n17",
$dieciocho => "n18",
$diecinueve => "n19",
$veinte => "n20",
$veintiuno => "n21",
$veintidos => "n22",
$veintitres => "n23",
$veinticuatro => "n24",
$veinticinco => "n25",
$veintiseis => "n26",
$veintisiete => "n27",
$veintiocho => "n28",
$veintinueve => "n29",
$treinta => "n30",
$treintayuno => "n31",
$treintaydos => "n32",
$treintaytres => "n33",
$treintaycuatro => "n34",
$treintaycinco => "n35",
$treintayseis => "n36",
$treintaysiete => "n37",
$treintayocho => "n38",
$treintaynueve => "n39",
$cuarenta => "n40",
$cuarentayuno => "n41",
$cuarentaydos => "n42",
$cuarentaytres => "n43",
$cuarentaycuatro => "n44",
$cuarentaycinco => "n45",
$cuarentayseis => "n46",
$cuarentaysiete => "n47",
$cuarentayocho => "n48",
$cuarentaynueve => "n49",
$cincuenta => "n50",
$cincuentayuno => "n51",
$cincuentaydos => "n52",
$cincuentaytres => "n53",
$cincuentaycuatro => "n54",
$cincuentaycinco => "n55",
$cincuentayseis => "n56",
);
krsort($naturales);
foreach ($naturales as $count => $name) {
echo "The \"$name\" appears $count times<br />";
}
Why my results are like this (Its hidding all the results with 12 (Similar count results)
for example for "n3" appears 12 times. and its not listed.
The "n20" appears 12 times
The "n30" appears 11 times
The "n37" appears 10 times
The "n41" appears 9 times
The "n42" appears 8 times
The "n45" appears 7 times
The "n47" appears 6 times
The "n35" appears 5 times
The "n44" appears 4 times
The "n46" appears 2 times
The "n56" appears 0 times
Build an array
$myresults = array("Item1"=>13,"item2"=>35,"item3"=>46);
then use asort() or arsort() on the array $myresults
then do a for/foreach loop to output the results
basic guidelines but off this you should be able to google how to implement in detail fairly easily (even on here will work)
$one = 13;
$two = 35;
$three = 46;
$arr = array("Item 1"=>$one,"Item 2"=>$two,"Item 3"=>$three);
echo "<strong>Original</strong><br />";
foreach($arr as $k => $v){
echo $k . " = " . $v . "<br />";
}
asort($arr);
echo "<strong>Ascending Sort</strong><br />";
foreach($arr as $k => $v){
echo $k . " = " . $v . "<br />";
}
arsort($arr);
echo "<strong>Descending Sort</strong><br />";
foreach($arr as $k => $v){
echo $k . " = " . $v . "<br />";
}
As previously mentioned, you can use asort and arsort to sort your array as needed... I'm adding some examples here as well as some working CODE
As mentioned, you could insert your values into an associative array, i.e.:
$items = array(
$one => "item1",
$two => "item2",
$three => "item3"
);
and then you can use a function like ksort() to sort all of your values:
http://php.net/manual/en/function.ksort.php
so you can end up with something like this:
ksort($items);
foreach ($items as $count => $name) {
echo "The \"$name\" appears $count times<br />";
}