Loop over one array and check if element exist in another array - php

I have two arrays, the first one is
$practice_areas = array(
array(
"id" => 1,
"name" => "Administrative",
"form_id" => 1
),
array(
"id" => 2,
"name" => "Admiralty & Maritime",
"form_id" => 1
),
array(
"id" => 3,
"name" => "Agricultural",
"form_id" => 1
),
array(
"id" => 4,
"name" => "Alternative Dispute Resulution",
"form_id" => 1
),
array(
"id" => 5,
"name" => "Antitrust & Trade Regulation",
"form_id" => 1
),
array(
"id" => 6,
"name" => "Appellate Practice",
"form_id" => 1
)
);
and the second one is $selected_id
$selected_id = array(
array(
"id" => 1,
"lawyer_id" => 2,
"practice_area_id" => 3
),
array(
"id" => 2,
"lawyer_id" => 2,
"practice_area_id" => 4
)
);
And this is my current code:
<label>Practice area(s) *</label>
<select id="practice_areas" multiple="multiple" name="practice_areas[]">
<option value="" selected="selected"></option>
<?php foreach($practice_areas as $practice_area) {?>
<option value="<?php $practice_area['id'] ?>" <?php ($selected_id->practice_area_id == $practice_area['id']) ? 'selected="selected"' : ''; ?>><?php $practice_area['name'] ?></option>
<?php } ?>
</select>
I want to select all the options that exist in the $selected_id array. I'm having a bad time on writing this loop correctly.
EDIT1
when I try to use the
foreach ($selected_id as $sel) {
$is_selected[$sel["practice_area_id"]] = true;
}
I've got this result.
$selected_id = array(
array(
"id" => 1,
"lawyer_id" => 2,
"practice_area_id" => 3
),
array(
"id" => 2,
"lawyer_id" => 2,
"practice_area_id" => 4
),
true,
true
);

You could do it like this:
<label>Practice area(s) *</label>
<select id="practice_areas" multiple name="practice_areas[]">
<option value="" selected></option>
<?php
// First create an array that is keyed by practice_area_id for selected items
foreach ($selected_id as $sel) {
$is_selected[$sel["practice_area_id"]] = true;
}
foreach($practice_areas as $practice_area) {
?>
<option value="<?= $practice_area['id'] ?>"<?=
(isset($is_selected[$practice_area['id']]) ? ' selected>' : '>') .
$practice_area['name'] ?></option>
</option>
<?php } ?>
</select>
Note that you had several <?php tags that did not echo anything inside the option tags. You can use instead the <?= tag for that.
Also the selected attribute in an option does not require a value. Just its presence is enough. The same goes for the multiple attribute of the select tag.
Finally, the -> operator only works on objects, but you have arrays, so you should use the bracket notation throughout.
See the above code run on eval.in

Related

How can I pass an array of hidden informations in a POST request in Cake 3.2?

I have created a form for a POST request, but I need to send an array of information that must be not visible in that form.
The array consist in a not specified number of other arrays.
My array is called "$dati" and is made by a not bounded number of arrays with three information each.
The code of my form is:
<?= $this->Form->create(null,['type'=> 'post', 'url'=>['action'=>'selectForSell2',$rassegnaselezionata->id,$showselezionato->id,$proiezioneselezionata->id ]]) ?>
<?= $this->Form->input('stato', ['options' => ['tutti' => 'Tutti i Soci', 'firmato' => 'Soci Firmati', 'approvato' => 'Soci Approvati'] ] ); ?>
<?= $this->Form->input('campo', ['options' => ['cognome' => 'Cognome', 'nome' => 'Nome', 'codicefiscale' => 'Codice Fiscale'] ] ); ?>
<?= $this->Form->input('ricerca', ['label' => false, "class" => " form-control input-medium", "placeholder" => __('Ricerca'), 'visible'=>false]); ?>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
In my projects, I have the following element as hidden.ctp:
if (isset($model)) {
$model .= '.';
} else {
$model = '';
}
foreach ($fields as $field => $values) {
if (is_array($values)) {
echo $this->element('hidden', ['model' => $model . $field, 'fields' => $values]);
} else {
echo $this->Form->hidden($model . $field, ['value' => $values]);
}
}
Then you can just call it with
echo $this->element('hidden', ['fields' => $dati]);
If you want to hidden the value of the array then you can do it in this way.
<?php
$a = array("Name" => "Peter", "Age" => "41", "Country" => "USA");
?>
<input type="hidden" name="data[Menu][arr]" value="<?php pr($a); ?>">
It can produce output like,when you post the data.Check it.it is required or not
Array
(
[Menu] => Array
(
[arr] => Array( [Name] => sradha [Age] => 20 [Country] => IN)
)
)

Use a foreach in 2 places php

I was trying to get the same result in two places with this code by including it with include(""); but after the first include goes right the second one gives me the last element of the array I made, the array is this one:
<?php
$aMenu = array(
array(
"title" => "Home",
"page" => "home",
),
array(
"title" => "Over mijzelf",
"page" => "mijzelf",
),
array(
"title" => "PC Games",
"page" => "games",
),
array(
"title" => "Video's maken",
"page" => "videos",
),
array(
"title" => "Basketball",
"page" => "basketball",
),
array(
"title" => "Fitness",
"page" => "fitness"
),
array(
"title" => "Toekomst",
"page" => "toekomst"
),
);
I call it here
foreach($aMenu as $aMenu) {
$sClass = '';
if ($aMenu["page"] == $_GET['page']) {
$sClass = 'class = "active" ';
}
/*echo $aMenu["title"];
echo $aMenu["page"];*/
echo '
<ul class=" nav nav-pills nav-stacked">
<li class="'.$sClass.'" role="presentation" >'.$aMenu["title"].'</li>
</ul>';
}
You overwrite your array while iterating:
foreach($aMenu as $aMenu)
Write something like this
foreach($aMenu as $entry)
so your iteration variable won't overwrite the array itself.

Sorting Multi-Dimensional Array PHP

I've that proceed this array in PHP
array(
"id" => 1,
"name" => "Carlos"
"other" => array("key" => "Hello")
),
array(
"id" => 3,
"name" => "Carlos"
"other" => array("key" => "Hello")
),
array(
"id" => 2,
"name" => "Carlos"
"other" => array("key" => "Hello")
)
and I need to order by "id". I've try it using usort and many multidimensional solutions but doesn't work for me.
I used that:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
But doesn't work because my array has many dimentions.
$departamento = $this->Departamentos->get($id, [
'contain' => [
'Asignaturas.Mallas',
'Asignaturas.Secciones.Perfiles',
'Asignaturas.Secciones.Mallas.Carreras',
'Unidades'
]
]);
That is my query in Cakephp. I need to order by Secciones.id
I used Hash::sort
http://book.cakephp.org/3.0/en/core-libraries/hash.html
And works fine for me ;)

how to get the value of textbox in the same in php

i am working on textbox in which value is display after selecting value from the combo box .i need to get that value that appear in textbox for further computation in the same page.
here is the coding
<?php
$options = array(
'0' => array(
'title' => ' ',
'value1' => '',
'value2' => '',
),
'1' => array(
'title' => 'Islamabad',
'value1' => '31.41',
'value2' => '73.11',
),
'2' => array(
'title' => 'Lahore',
'value1' => '31.56',
'value2' => '74.35',
),
'3' => array(
'title' => 'Kharachi',
'value1' => '24.86',
'value2' => '67.01',
),
'4' => array(
'title' => 'Faisalâbâd',
'value1' => '31.41',
'value2' => '73.11',
),
'5' => array(
'title' => 'Gujrânwâla',
'value1' => '32.16',
'value2' => '74.18',
),
);
if (isset($_GET['option']) && isset($options[$_GET['option']])) {
echo json_encode($options[$_GET['option']]);
exit;
}
?>
<form>
<?php echo "SELECT " ?>
<select name="combo" id="combo">
<?php
foreach($options as $key_value => $option)
{
printf('<option value="%s">%s</option>', $key_value, $option['title']);
}
?>
</select>
<input type="text" name="hidden" id="textboxB" value="" />
<input type="text" name="hidden" id="textboxC" value="" />
<script type="text/javascript" src="jquery.min1.js"></script>
<script type="text/javascript">
$(function(){
$('#combo').change(function(){
$.getJSON("?", {
option : $(this).val()
}, function (data) {
$('#textboxB').val(data.value1);
$('#textboxD').val(data.value1);
$('#textboxE').val(data.value1);
$('#textboxC').val(data.value2);
});
});
});
</script>
i need to get the value of textboxB and textboxC in separate variable so that i can use theses value for further computation on the same page.
i want to use theses value in if -else statement like
if(textboxD==3.15)
{
$a=$b......
}
my requirement is to get these value in separate variable.
people plz help me in ths
You need to set your input names to arrays, such as:
<input type="text" name="hidden[]" id="textboxA" value="123" />
<input type="text" name="hidden[]" id="textboxB" value="654" />
<input type="text" name="hidden[]" id="textboxC" value="abc" />
<input type="text" name="hidden[]" id="textboxD" value="zyg" />
Remember, ID's are only useful for client-side. ID's never get posted, only the NAME and VALUE.
Now, in PHP, you can access these values via:
<?php
$hidden = !empty($_POST['hidden']) ? $_POST['hidden'] : false;
if($hidden) {
foreach($hidden as $key => $value) {
echo "$key => $value\n"; // 0 => 123, 1 => 654, etc.
}
// Directly access single item:
echo $hidden[3]; // zyg
}
?>

Put nested array into one array

Suppose i have a array like this :
Array(
'1' => Array(
"ID" => 1,
"Name" => "name 1"
),
'2' => Array (
Array(
"ID" => 2,
"Name" => "name 2"
)
),
'3' => Array(
Array(
Array(
Array(
"ID" => 3,
"Name" => "name3"
)
)
),
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
number of sub-arrays is not ordered it may be 3, 4 or 5 etc...
and i wanted to get :
Array(
Array( "ID" => 1, "Name" => "name 1"),
Array( "ID" => 2, "Name" => "name 2"),
Array( "ID" => 3, "Name" => "name 3"),
Array( "ID" => 4, "Name" => "name 4"),
Array( "ID" => 5, "Name" => "name 5"),
Array( "ID" => 6, "Name" => "name 6"));
Is there an easy way to do this ?
EDIT :
Edited the above array to add :
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
which aren't nested but i still want them to be in my final array.
Thanks.
//Assuming your data is in $in
$out=array();
foreach($in as $k=>$v) {
while ((is_array($v)) && (isset($v[0]))) $v=$v[0];
//See below for next line
$out[]=$v;
}
print_r($out);
With the marked line being either $out[$k]=$v; or $out[]=$v; depending on wether you want to keep the 1st-level keys. In your desired output you do not ,so use the shown version
Edit
With you changed input array, you need to do something like
function addtoarray($inarray, &$outarray) {
foreach ($inarray as $i) {
if (!is_array($i)) continue;
if (isset($i['ID'])) $outarray[]=$i;
else addtoarray($i,$outarray);
}
}
$out=array();
addtoarray($in,$out);
print_r($out);
This was tested against your new input data
You could recurse through the array and check for the ID field.
function combine_array(array $src, array &$dest)
{
if( isset( $src['ID'] ) ) {
$dest[] = $src;
return;
}
foreach( $sub in $src ) {
combine_array( $sub, $dest );
}
}
Just wrote this off the top of my head, no testing, so it might have a few problems. But that's the basic idea.
This may work for you, assuming $array is the variable and php 5.3
//process
$array = array_map(function($block) {
$return = '';
foreach ($block as $sub) {
if (true === isset($sub['ID']) {
$return = $block;
break;
}
}
return $block;
}, $array);
array_filter($array); //remove empty elements
Wrote up a quick recursive function. You'll need to write any appropriate error handling and check the logic, since a discrepancy in your data could easily turn this into an infinite loop:
$output = array();
foreach ( $data as $d ) {
$output[] = loop_data( $d );
}
function loop_data( $data ) {
// Check if this is the right array
if( ! array_key_exists( "ID", $data ) ) {
// Go deeper
$data = loop_data( $data[0] );
}
return $data;
}

Categories