How to use the foreach inside array in php? - php

I am trying to do foreach inside array.
I am trying to generate the select box using array value everything seems ok when i give a value manually.
array(
'name' => __('Testing Selection', 'test'),
'id' => 'testing',
'css' => 'min-width:150px;',
'std' => '2',
'default' => '2',
'type' => 'select',
'options' => array(
'1' => __('Test1', 'test'),
'2' => __('Test2', 'test'),
'3' => __('Test3', 'test'),
),
),
In the above code options key contains three values like 1, 2, 3 and the above code is working. But i want to loop all product id here using foreach but it seems not working for me may be i am trying a wrong way. I know foreach inside array is invalid that's why i am trying this way.
$foos = array(
'name' => __('Testing Selection', 'test'),
'id' => 'testing',
'css' => 'min-width:150px;',
'std' => '2',
'default' => '2',
'type' => 'select',
'options' => array(),
),
After array i did foreach
$args = array('post_type' => 'product', 'posts_per_page' => '-1');
$getproducts = get_posts($args);
foreach ($getproducts as $product) {
$foos['options'][] = array(
$product->ID => $product->get_title,
);
}
I want to list 20 more products in the select box everything manually is hard to me can anyone suggest me to use the foreach inside array?

With PHP functions like array_map() or array_reduce() you can create the new array inside an array. array_map () is useful for creating the values ​​for an array, but you can not manipulate the keys with it. Because of that we can use array_reduce() to simulate the behavior of array_map() and to create the associative array needed for options.
$foos = array(
'name' => 'Testing Selection',
'id' => 'testing',
'css' => 'min-width:150px;',
'std' => '2',
'default' => '2',
'type' => 'select',
'options' => array_reduce( get_posts( 'post_type=product&posts_per_page=-1' ), function( $result, $item ) {
$result[$item->ID] = $item->post_title;
return $result;
})
);
If you don't like the approach, you can create new function that will return the required array for options, and thus improve the readability of code.

I'm not sure exactly what you have in mind, but try this template:
<select>
<?php
$items = array(
'one' => 'Item one',
'two' => 'Item two',
'three' => 'Item three'
);
foreach(array_keys($items) as $item_id) {
echo "<option name=\"$item_id\">$items[$item_id]</option>\n";
}
?>
</select>

If you want to insert data to database , then you should go with foreach key value combination.
Here given the example
<?php
if(isset($_POST['submit'])){
$myArray = array();
$myArray = array(
'name' => $_POST['name'],
'contact' => $_POST['contact'],
'address' => $_POST['address']
);
foreach($myArray as $key=>$value){
echo $value;
}
}
?>
<html>
<head>
</head>
<body>
<form action="#" method="post">
name<input type="text" name="name"/>
contact<input type="text" name="contact"/>
address<input type="text" name="address"/>
<input type="submit" name="submit"/>
</form>
</body>
</html>

Related

How to get a specific value based on adjacent key from a keyless multidimensional array?

Consider the following array:
$serviceNames = array(
0 => array(
'language' => 'en',
'value' => 'something',
'type' => 'name',
),
1 => array(
'language' => 'fi',
'value' => 'jotain',
'type' => 'name',
),
2 => array(
'language' => 'sv',
'value' => 'någonting',
'type' => 'name',
),
);
I need to get the 'value' definitions based on language. The problematic part is that the array $serviceNames does not have a predefined length (comes originally as a JSON file from an API), and the items can come in any order (in my example it goes like en, fi, sv, but it could be de, en, sv, fr... you get it).
If I wanted to get 'value' within the array where 'language' equals to 'en', how could I do that?
My advice is that you make the array associative.
Once that is done you access the value by ["language"]["value"].
$serviceNames = array_column($serviceNames, Null, "language");
echo $serviceNames["fi"]["value"]; //jotain
echo $serviceNames["en"]["value"]; //something
echo $serviceNames["sv"]["value"]; //någonting
https://3v4l.org/ssGQa
You can array_search() and array_column() function. first find the key where "en" is in the array then get the value.
$key = array_search('en', array_column($serviceNames, 'language'));
echo $serviceNames[$key]['value'];
Demo
simple:
$serviceNames = array(
0 => array(
'language' => 'en',
'value' => 'something',
'type' => 'name',
),
1 => array(
'language' => 'fi',
'value' => 'jotain',
'type' => 'name',
),
2 => array(
'language' => 'sv',
'value' => 'någonting',
'type' => 'name',
),
);
function myfunction(array $serviceNames, $field)
{
foreach($serviceNames as $service)
{
if ( $service['language'] === $field )
return $service['value'];
}
return false;
}
echo myfunction($serviceNames, 'en');
Output will : something
you would have to go through each elements of the array, using the foreach statement.
something like:
function getValueForLang($lang, array $arr)
{
foreach ($arr as $desc) {
if ($desc['language'] == $lang) {
return $arr['value'];
}
}
return null;
}
getValueForLang('en', $serviceNames); // gets your value, null if not found
see also:
https://secure.php.net/manual/en/control-structures.foreach.php

YII - Set data in dropdownlist from 2 array using CHtml::listData

I have 2 arrays. The First array will be the key and the second will be the value. How can I make the data in dropdownlist from these arrays?
Here is my code:
<?php
echo $form->dropDownListGroup($model, 'arrival_code', array(
'prepend' => '<i class="glyphicon glyphicon-map-marker"></i>',
'widgetOptions' => array(
'data' => array('1' => 'Satu', '2' => 'Dua', '3' => 'Tiga'),
'htmlOptions' => array(
'prompt' => 'Tujuan'
),
),
));
?>
I want the data will be fill from 2 arrays. Thanks.
You can try this one
$new_arr = array_combine($keys, $values);
echo CHtml::dropDownList('listname', $select, $new_arr);

How to populate list box in yii by using the following code

$selected = array( '5' => array('selected' => 'selected'),'6' => array('selected' => 'selected'),);
$htmlOptions = array('size' => '5', 'prompt'=>'Use CTRL to Select Multiple Staff', 'multiple' => 'true', 'options' => $selected);
echo $form->listBox($model,'team_members', $mem_arr, $htmlOptions);
From the above code it works properly. But I have selected variable as an array variable..
then how do i give instead of '$selected' array
If I understand your question correctly, you could do this (not tested):
$result = array(5,6);
$selected = array():
foreach ($result as $selectedIndex) {
$selected[$selectedIndex] = array('selected'=>'selected');
}
$htmlOptions = array(
'size' => '5',
'prompt'=>'Use CTRL to Select Multiple Staff',
'multiple' => 'true',
'options' => $selected);
echo $form->listBox($model,'team_members', $mem_arr, $htmlOptions);

How i get the real value in select form zf2

I need to get the real value, instead of the number position of a Select form field
I explain it with one example:
first in the form
$procesa=new Querys();
$datosAsignaturas=$procesa->getDatosAsignaturas();
$groups = array();
foreach ($datosAsignaturas as $id => $list) {
$groups[$id] =$list["nombreA"];
}
$selection= $factory-> createElement(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'subjects',
'attributes' => array(
'id' => 'subjects',
'options' => $groups
),
));
$this->add($selection);
Second, the view
<div class="form_element">
<?php $element = $form->get('subjects');
?>
<label>
<?php echo $element->getOption('value'); ?>
</label>
<?php echo $this->formSelect($element); ?>
</div>
third
["subjects"]=> string(1) "1"
i need something like this
["subjects"]=> string(1) "Maths"
Proper assignement of values to a Zend\Form\Element\Select is through the means of value_options inside options or using the element function setValueOptions(). Here a simple example:
$form->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'language',
'options' => array(
'label' => 'Which is your mother tongue?',
'empty_option' => 'Please choose your language',
'value_options' => array(
'0' => 'French',
'1' => 'English',
'2' => 'Japanese',
'3' => 'Chinese',
),
)
));
Now if you need to access the value options like this, you simply call getValueOptions() on the element and you'll receive exactly the same array as above. Then you could do something like this (which I'm assuming is what you're trying to do):
$elemLanguage = $form->get('language');
echo "<select name='{$elemLanguage->getName()}'>\n";
foreach($elemLanguage->getValueOptions() as $id => $language) {
echo "<option value='{$id}'>{$id} - {$language}</option>\n";
}
echo '</select>';
Maybe you mean :
<div class="form_element">
<?php $element = $form->get('subjects');
?>
<label>
<?php echo $element->getOption('label'); //-------- label instead value?>
</label>
<?php echo $this->formSelect($element); ?>
</div>
And about the form
$procesa=new Querys();
$datosAsignaturas=$procesa->getDatosAsignaturas();
$groups = array();
foreach ($datosAsignaturas as $id => $list) {
$groups[$id] =$list["nombreA"];
}
$selection= $factory-> createElement(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'subjects',
'attributes' => array(
'id' => 'subjects',
'options' => $groups
),
'options'=>array(
'label'=>"Your label",
'description' => 'your description',
'value_options' => array(
'0' => 'French',
'1' => 'English',
'2' => 'Japanese',
'3' => 'Chinese',
),
)
));
$this->add($selection);

Displaying tag names rather than IDs using the form helper

In one of my forms I have a text input for a posts tags. At the moment, Cake is returning the tag id into this field rather than the name of the tag. I want to change it to show the name of the tag.
The posts controller is getting a result like this:
array(
'Post' => array(
'id' => '7',
'title' => 'Testing again',
'body' => 'wooooooo',
'created' => '2013-01-09 19:20:53',
'slug' => 'testing-again'
),
'Tag' => array(
(int) 0 => array(
'id' => '4',
'name' => 'tag1'
),
(int) 1 => array(
'id' => '3',
'name' => 'tag2'
),
(int) 2 => array(
'id' => '5',
'name' => 'tag3'
)
)
)
and the form is laid out like this:
<?php echo $this->Form->create('Post'); ?>
<?php echo $this->Form->input('Post.title'); ?>
<?php echo $this->Form->input('Post.body'); ?>
<?php echo $this->Form->input('Tag.Tag', array('type' => 'text', 'label' => 'Tags (seperated by space)')); ?>
<?php echo $this->Form->input('Post.slug'); ?>
<?php echo $this->Form->end('Save Changes'); ?>
Is there a way I can tell CakePHP to output the name field of the tags instead of id? Thanks.
OK, so from what I've gathered from our comment discussion, this would be what you're looking for. In your controller, just loop over all the set tags for the post. Assuming your find result is set in the $post variable, you can use the below code and save them all in a "plain" non-recursive array:
$tags = array(); // This will hold all the tags
foreach($post['Tag'] as $tag) {
$tags[] = $tag['name'];
}
// Set the tags as view variable
$this->set(compact('tags'));
Then in your view you can just implode the array with a space and set it as value for your text field:
echo $this->Form->input('Tag.Tag', array('type' => 'text', 'label' => 'Tags (seperated by space)', 'value' => implode(' ', $tags)));
The find example in your OP would then return a value of tag1 tag2 tag3.
Did you set the $displayField in the tags model?
eg.
public $displayField = "name";

Categories