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>
Related
I am having a $_POST array look like this:
Array
(
[veryfy_doc_type] => Array
(
[0] => 1
[1] => 2
)
[id_number] => Array
(
[0] => 3242424
[1] => 4456889
)
[document_issuer] => Array
(
[0] => 1
[1] => 3
)
[verify_doc_expiry_date] => Array
(
[0] => 2016-01-26
[1] => 2015-02-20
)
[doc_id] => Array
(
[0] => 15
[1] => 16
)
[user_id] => Array
(
[0] => 14
[1] => 14
)
)
Using this array I need to get each values into php variables.
I tried it something like this, but it doesn't work for me.
foreach($_POST AS $k => $v) {
//print_r($v);
list($doc_type, $id_number, $issuer, $expiry_date, $doc_id, $user_id) = $v;
}
echo "Type = $doc_type";
Can anybody tell me how to figure this out.
Thank you.
This might help you since you can also use extract in php to create variables.
<?php
$_POST = array(
'veryfy_doc_type'=> array(1,2),
'id_number' => array(3242424,4456889),
'document_issuer'=> array(1,3),
'verify_doc_expiry_date'=> array('2016-01-26','2015-02-20'),
'doc_id' => array(15,16),
'doc_id' => array(14,14)
);
extract($_POST);
print_r($veryfy_doc_type);
print_r($id_number);
So you want to reference each of the sub-array values while looping the main array... maybe something like this?
// Loop one of the sub arrays - you need to know how many times to loop!
foreach ($_POST['veryfy_doc_type'] as $key => $value) {
// Filter the main array and use the $key (0 or 1) for the callback
$rowValues = array_map(function($row) use ($key) {
// Return the sub-array value using the $key (0 or 1) for this level
return $row[$key];
}, $_POST);
print_r($rowValues);
}
Example: https://eval.in/498895
This would get you structured arrays for each set of data.
From here I'd suggest you leave the arrays as they are rather than exporting to variables, but if you wanted to you you could use the list() as in your example.
You can use a MultipleIterator for that:
<?php
$post = array(
'veryfy_doc_type' => array('1','2'),
'id_number' => array('3242424','4456889'),
'document_issuer' => array(1,3),
'verify_doc_expiry_date' => array('2016-01-26','2015-02-20'),
'doc_id' => array(15,16),
'user_id' => array(14,14)
);
$mit = new MultipleIterator(MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_ASSOC);
foreach($post as $k=>$v) {
$mit->attachIterator( new ArrayIterator($v), $k);
}
foreach( $mit as $row ) {
echo $row['doc_id'], ' ', $row['id_number'], ' ', $row['verify_doc_expiry_date'], "\r\n";
}
prints
15 3242424 2016-01-26
16 4456889 2015-02-20
If you have control over the client code you can change the names of the POST parameters in a way that php build this structure automagically. E.g.
<form method="POST" action="test.php">
<input type="hidden" name="record[0][veryfy_doc_type]" value="1" />
<input type="hidden" name="record[0][id_number]" value="3242424" />
<input type="hidden" name="record[0][document_issuer]" value="1" />
<input type="hidden" name="record[0][verify_doc_expiry_date]" value="2016-01-26" />
<input type="hidden" name="record[0][doc_id]" value="15" />
<input type="hidden" name="record[0][user_id]" value="14" />
<input type="hidden" name="record[1][veryfy_doc_type]" value="2" />
<input type="hidden" name="record[1][id_number]" value="4456889" />
<input type="hidden" name="record[1][document_issuer]" value="3" />
<input type="hidden" name="record[1][verify_doc_expiry_date]" value="2015-02-20" />
<input type="hidden" name="record[1][doc_id]" value="16" />
<input type="hidden" name="record[1][user_id]" value="14" />
<input type="submit" />
</form>
would do/cause that.
If you only want to get the value of the post then you can have a simple multidimentional loop. no need to make it broad
foreach($_POST as $keyName => $row){
// $keyName will be verify_doc_type, id_number, etc..
foreach($row as $value){
// do something
echo $value;
}
}
Hope that helps.
This method will generate variables of same name as in POST array:
foreach ($_POST as $k => $v )
{
$$k = addslashes(trim($v ));
}
I know this post is a bit old, but I was recently trying to achieve this very same thing.
Hopefully the answer will point others in the right direction.
As per the documentation on list():
Since PHP 7.1, keys can be specified
Example from the manual:
<?php
$arr = ['locality' => 'Tunis', 'postal_code' => '1110'];
list('postal_code' => $zipCode, 'locality' => $locality) = $arr;
echo $zipCode; // will output 1110
echo $locality; // will output Tunis
?>
https://www.php.net/manual/en/function.list.php#121094
I received help already with a previous question about posting an array.
Now I'm trying to add more arrays to the loop
Here's the html
<input class="input stickyinput" type="number" name="pestcount[]">
<input type="hidden" name="cardtype[]" value="<?= htmlspecialchars($obj['cardtype']) ?>" />
<input type="hidden" name="cardid[]" value="<?= htmlspecialchars($obj['card_id']) ?>" />
<input type="hidden" name="pestname[]" value="<?= htmlspecialchars($pestname['scoutlogpestname']) ?>" />
Here's the php
for ($i=0; $i < count($_POST['cardid']); $i++ ) {
$card_id = $_POST['cardid'][$i];
$card_type = $_POST['cardtype'][$i];
$pest_count = $_POST['pestcount'][$i];
$pest_name = $_POST['pestname'][$i];
$sql ="INSERT INTO scout_logpestnum (pest_name,pest_count,card_id,card_type)
VALUES (:pest_name,:pest_count,:card_id,:card_type)";
$q = $pdo->prepare($sql);
$q->execute(array(':pest_name'=>$pest_name,':pest_count'=>$pest_count,':card_id'=>$card_id,':card_type'=>$card_type));
}
So what is the proper format for adding addition arrays from the form?. Thanks;)
Here's what my array looks like.
Array (
[pestcount] => Array (
[0] => 1
[1] => 2
[2] => 3
)
[cardtype] => Array (
[yellcard] =>
)
[cardid] => Array (
[1] =>
)
[pestname] => Array (
[Aphids] =>
[Thrips] =>
[White-Fly] =>
)
Assuming that pests and cards are separate collections, you can simply use a prefix to identify them in $_POST data. For example...
<input name="pests[<?= htmlspecialchars($pestname['scoutlogpestname']) ?>][<?= $obj['card_id'] ?>]" ...
and
<input name="cards[<?= htmlspecialchars($obj['cardtype']) ?>][<?= $obj['card_id'] ?>]" ...
This would produce HTML like
<input name="pests[Aphids][1]" ...
<input name="cards[yellcard][1]" ...
Then, in your form handler...
$pests = $_POST['pests'];
foreach ($pests as $pest_name => $values) {
foreach ($values as $card_id => $pest_count) {
echo $pest_name, $card_id, $pest_count;
}
}
$cards = $_POST['cards'];
foreach ($cards as $card_type => $values) {
foreach ($values as $card_id => $value) {
echo $card_type, $card_id, $value;
}
}
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'];
}
}
}
}
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 />";
}
I need to create an array where i can use 1,2,3 but have 1v1, 2v2, Clubs associated with them.
I am going to use 1,2,3 for option value and 1v1,2v2 and clubs to display to the user.
How can I store this in an array and then use foreach to extract?
Thanks
$data = array(
1 => '1v1',
2 => '2v2',
3 => 'Clubs';
);
echo '<select>';
foreach($data as $value => $title) {
echo '<option value="'.$value.'">'.$title.'</option>';
}
echo '</select>';
You can make your original values (1,2,3) the keys and the (1v1, 2v2, Clubs) the values.
$data = array(1 => '1v1', 2 => '2v2', 3 => 'Clubs');
foreach($data as $key => $value) {
print $key.' - '.$value.'<br/>';
}
Maybe, I don't understand your question. try to use the next array:
$array = array(1 => '1v1', 2 => '2v2');
And foreach:
<select>
<? foreach ($array as $k => $v) { ?>
<option value="<?= $k ?>"><?= $v ?></option>
<? } ?>
</select>
I don't fully understand the question, but it seems like you want to map the values 1,2,3 to the text '1v1','2v2','Clubs'. PHP supports associative arrays that are suitable for this purpose:
$a = Array(
1 => '1v1',
2 => '2v2',
3 => 'Clubs'
);