Pay attention to the options array this array holds an array of properties on the database, there is a call for the database in the script it's not nessecary to add here, it retrieves the data because it's already on there...
$meta_boxes[] = array(
'id' => 'page_metabox',
'fields' => array(
array(
'name' => ''.$slider['properties']['title'].'',
'desc' => 'Upload an image/pattern for the static area.',
'id' => $prefix . 'text_BOMB',
'type' => 'sortable',
'options' => $slider['properties'],
'multiple' => true,
),
);
The data HTML is outputted using a foreach and an input...
<?php foreach ( $field['options'] as $value => $name ) : ?>
<input type="text" name="<?php echo $field['id'].'[]' ?>" id="<?php echo $field['id'] ?>" value="<?php echo $value; ?>" />
<?php endforeach; ?>
This is exactally what I want, I have a list of inputs for each property... then it hit me, what if its a new user and the data isnt on their database yet the foreach wont output anything and then there is no way to write it to the database... this is pretty noobish but that means an easier answer for you guys :p
You could use empty - function:
<?php
if (empty($field['options'])) {
//do something when options are empty
}
else { //the array $field['options'] has something in it
foreach ( $field['options'] as $value => $name ) : ?>
<input type="text" name="<?php echo $field['id'].'[]' ?>" id="<?php echo $field['id'] ?>" value="<?php echo $value; ?>" />
<?php endforeach;
}
?>
Related
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 } ?>
I'm trying to post and receive a two dimensional array, but I can't get it to work.
Could you guys help me out?
Thanks in advance!
Here is my code:
$items[] = array(
'pid' => $pid
, 'qty' => $product_qty
);
<input type="hidden" name="items[]" id="pid" />
foreach ($_POST['items'] as $row) {
$pid = $row['pid'];
$product_qty = $row['qty'];
}
Change your code in a way like this:
$items = array('pid' => $pid, 'qty' => $product_qty);
foreach( $items as $key => $val )
{
echo '<input type="hidden" name="items['.$key.']" value="'.$val.'" id="'.$key.'" />';
}
In your original code, $items[] add a new item to array $items.
Also, HTML doesn't interpret php variables, so your <input name="items[]" will produce $_POST[items][0] with an empty value.
It's as simple as this:
$myarr = array( 'pid' => array($pid), 'qty' => array($product_qty));
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 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
I am trying to create a php array from posted values and then json_encode to achieve this:
[{"network_type":"facebook","network_url":"fb.com/name"},{"network_type":"twitter","network_url":"#name"},{"network_type":"instagram","network_url":"#name"}]
which after json_decode looks like:
array(
[0] => stdClass(
network_type = 'facebook'
network_url = 'fb.com/name'
)
[1] => stdClass(
network_type = 'twitter'
network_url = '#name'
)
[2] => stdClass(
network_type = 'instagram'
network_url = '#name'
)
)
My php looks like this:
$social_data = array(
'network_type' => $this->input->post('network_type'),
'network_url' => $this->input->post('network_url')
);
and so the array is not grouped the way I want it, but rather by the field name:
array(
['network_type'] => array(
[0] => 'facebook'
[1] => 'twitter'
[2] => 'instagram'
)
['network_url'] => array(
[0] => 'fb.com/name'
[1] => '#name'
[2] => '#name'
)
and therefore the result of the json_encode isn't grouped how I want it:
{"network_type":["facebook","twitter","instagram"],"network_url":["fb.com/name","#name","#name"]}
)
So the question is...how do I adjust my php so the array is correct?
--- here's the input fields:
<?php
foreach ($social as $key => $value) {?>
<p>
<label for="network_type"><input type="text" size="20" name="network_type[]" value="<?php echo $value -> network_type; ?>" placeholder="Social Network" /></label>
<label for="network_url"><input type="text" size="20" name="network_url[]" value="<?php echo $value -> network_url; ?>" placeholder="URL or Handle" /></label>
<a class="remNetwork" href="#">Remove</a>
</p>
<?php } ?>
----latest update: this is sooooo close!-----
Ok, for some reason (probably me botching things one way or another), both suggested methods below didn't quite get me there....but, a mix of both methods has gotten me close:
This if/loop/array setup:
$network_type = (array)$this->input->post('network_type', true);
$network_url = (array)$this->input->post('network_url', true);
$social_data = array();
if (($counter = count($network_type)) == count($network_url)){
for($i = 0;$i < $counter; $i++) {
$social_data[$i] = array(
'network_type' => $this->input->post('network_type[$i]'),
'network_url' => $this->input->post('network_url[$i]'),
);
}
}
paired with this input loop:
<?php
foreach ($social as $key => $value) {
?>
<p>
<label for="network_type"><input type="text" size="20" name="network_type[]" value="<?php echo $value -> network_type; ?>" placeholder="Social Network" /></label>
<label for="network_url"><input type="text" size="20" name="network_url[]" value="<?php echo $value -> network_url; ?>" placeholder="URL or Handle" /></label>
<a class="remNetwork" href="#">Remove</a>
</p>
<?php } ?>
is yielding the following:
array(
[0] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
[1] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
[2] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
)
So, I think if I can figure out why these values are false, then we've done it!
Thanks and appreciation for your patience and help in advance...
-- update again ----
To my dismay, I've left out a piece that's perhaps critical...the coffee script that's dynamically creating the form fields when there's more than one social:
$ ->
socialDiv = $("#social")
i = $("#social p").size() + 1
index = 0
$("#addNetwork").click ->
$("<p><label for=\"network_type[]\"><input type=\"text\" id=\"network_type[]\" size=\"20\" name=\"network_type[]\" value=\"\" placeholder=\"Social Network\" /></label><label for=\"network_url[]\"><input type=\"text\" id=\"network_url[]\" size=\"20\" name=\"network_url[]\" value=\"\" placeholder=\"URL or Handle\" /></label> Remove</p>").appendTo socialDiv
i++
false
$(document).on "click", ".remNetwork", ->
#$(".remNetwork").bind "click", ->
if i > 1
$(this).parent("p").remove()
i--
false
In your example, i can asume that network_type and network_url are inputs like:
<input type="text" name="network_type[]" /> and <input type="text" name="network_url[]" />
so in order to accomplish what you want you would:
<?php
$networkType = (array)$this->input->post('network_type', true);
$networkUrl = (array)$this->input->post('network_url', true);
$networkData = array();
if (($counter = count($networkType)) == count($networkUrl)) {
for ($i = 0; $i < $counter; ++$i) {
$networkData[] = array(
'network_type' => $networkType[$i],
'network_url' => $networkUrl[$i]
);
}
}
?>
and should give you the desired json.
However, this approach is a bit clunky and unreliable.
Instead, i would define the input fields like:
<input type="text" name="network[0][network_type]" /> and <input type="text" name="network[0][network_url]" />
<input type="text" name="network[1][network_type]" /> and <input type="text" name="network[1][network_url]" />
and i would generate the php array like:
<?php
$networkData = (array)$this->input->post('network', true);
?>
Just my two cents :)
L.E:
To make it detailed and create the std objects from your array, you would:
$networkData = array();
if (($counter = count($networkType)) == count($networkUrl)) {
for ($i = 0; $i < $counter; ++$i) {
$obj = new StdClass();
$obj->network_type = $networkType[$i];
$obj->network_url = $networkUrl[$i];
$networkData[] = $obj;
}
}
print_r($networkData);
You can use a for loop to iterate through as you feed them into the $social_data array. It would be
for($i = 0;$i < $items.length;$i++) {
$social_data[$i] = array(
'network_type' => $this->input->post('network_type[$i]'),
'network_url' => $this->input->post('network_url[$i]'),
);
The resulting array will look like:
$social_data[0] ->
'network_type' => 'facebook',
'network_url' => 'fbook.com/user'
$social_data[1] ->
...etc
I'm not totally sure what context you're getting the network_type and url but they will both be arrays and looping through for each individual value is what to do. Without the rest of the code it's hard to get much more specific but hopefully this will point you in the right direction.