Array manipulation to create a dropdown box cakephp - php

this is my problem
i,ve to create a dropdown list box from a table states('id','state_name') which is not my default model( which has many fields one of the field is 'state' in which i store states('id') .
so i used loadModel to populate the drop down box.
in my controller i used
$this->loadModel('State');
$this->set('states',$this->State->find('all'));
in the view side
$form->select('State_id',$states);
in the output the table name, the id and name are displaying.
when i printed $states using pr();
what i got was
Array
(
[0] => Array
(
[State] => Array
(
[id] => 1
[state_name] => state1
)
)
[1] => Array
(
[State] => Array
(
[id] => 2
[state_name] => state2
)
)
and so on
how to create an array like array(1=>state1, 2=>state2) from the above array
or is there any other way to create a dropdown listbox
kindly help

This is the way:
$fields = array('id','state_name');
$states = $this->State->find('list',array('fields'=>$fields));
$this->set(compact('states'));
or in one line:
$this->set('states',$this->State->find('list',array('fields'=>array('id','state_name'))));

The below code will create the array you wanted from the original array
$newstates = array();
foreach($states as $state) {
$state = $state['State']
$newstates[$state['id']] = $state['state_name'];
}
print_r($newstates);
Result:
Array
(
[1] => state1
[2] => state2
)

Related

How to arrange 2 simple array data

I have array data attached in below image and i want to show it exactly like
Array
(
[0] => Array
(
[title] => VALID Act Introduction Advances Diagnostics Regulatory Reform
[link] => https://www.advamed.org/newsroom/press-releases/valid-act-introduction-advances-diagnostics-regulatory-reform
)
[1] => Array
(
[name] => MedTech Fighting Coronavirus on Multiple Fronts
[category] => https://www.advamed.org/newsroom/press-releases/medtech-fighting-coronavirus-multiple-fronts
)
[2] => Array
(
[title] => EPA Ethylene Oxide Value at Odds with Public Health, Best Science
[link] => abc
)
)
Lets say your first data stored in $Title array and second one stored in $Link array. Now populate those in $Data array.
$Data = [];
foreach($Title as $key=>$value){
$Data[] = [
'title'=>$value,
'link'=>$Link[$key]
];
}
in $Data you'll get your desired output.
so finally below is my solution. we just need to sort it out with array map function.
$results = array_map(null , $title, $url);

array index changing into string [name] not number

I have form (display.php) that will get multiple selected option from user. Then this selected option will be formatted to another page (page.php). The problem occur when I try to display those multiple selected option. The array index are changing into string [name]!
Array ( [0] => 3204120006 [1] => 3204120011 [2] => 3204120010 [3] => 3204120009 )
Array ( [name] => BIRU ) Array ( [name] => BOJONG ) Array ( [name] => MAJAKERTA ) Array ( [name] => MAJALAYA )
Here the code of above display.
<?php
if (isset($_POST["desas"])) {
$ddes=$_POST["desas"];
print_r ($ddes);
foreach ( $ddes as $iddesa ) {
$namadesa=mysql_query("SELECT name FROM villages WHERE id='$iddesa' ");
if ($namadesa) {
$datadesa = mysql_fetch_assoc($namadesa);
print_r($datadesa);
}
} else
$datadesa="";
}
?>
My question is how to change ([name]=>BIRU),([name]=>BOJONG) into index ([0]=>BIRU),([1]=>BOJONG) etc on those array? or something missing in mysql fetch?
you can use array_values. reference: https://secure.php.net/manual/en/function.array-values.php
$datadesa = array_values(array_values);

Sort array based on key value

I'm using a form where the pair of inputs can be added per automatic. One store value in select and the other as input
After submit I receive the values in array and I need to associate them together. So all key values [0] belongs together and all [1] and so on.
Array
(
[issue] => Array
(
[0] => 2
[1] => 3
)
[qty] => Array
(
[0] => 1
[1] => 2
)
)
How can I do this using PHP?
Just use a simple foreach loop.
$combined = array();
foreach ($_POST["issue"] as $k=>$v) {
$combined[$k] = array($_POST["issue"][$k], $_POST["qty"][$k]);
}
print_r($combined);

PHP - Access an array using another array as the key

I'm creating a class that assists in building settings pages for WordPress plugins. The developer instantiates the class by passing in an array of settings. A basic example looks like:
Array
(
[textbox1] => Array
(
[title] => Textbox
[type] => text
[section] => general
[desc] => The text description
)
[a_nice_dropdown] => Array
(
[title] => Select me
[type] => select
[section] => general
[desc] => The select description
[choices] => Array
(
[red] => Red
[blue] => Blue
[green] => Green
)
)
)
This works fine. My class builds the options page and the inputs have HTML that looks like:
<input id="textbox1" type="text" name="options_slug[textbox1]" value="">
When "Save Changes" is clicked, my class grabs all the options tied to "options_slug" and stores them in a single wp_options entry as a nice serialized array, making it easy to grab later.
The New Challenge
I have a new project which requires multiple nested "repeater" fields, similar to the way Advanced Custom Fields handles it. I've created a new field type, to handle this, which can support "subfields". An example config output (from error_log) looks like:
Array
(
[subfields_container] => Array
(
[title] => Subfields
[type] => subfields
[section] => general
[desc] => This is the subfields description text
[subfields] => Array
(
[textbox2] => Array
(
[title] => Textbox
[type] => text
[section] => general
[desc] => The text description
)
[select1deep] => Array
(
[title] => Subfield Select
[type] => select
[choices] => Array
(
[1] => 1
[2] => 2
[3] => 3
)
[std] => 1
)
)
)
)
I've configured the HTML output so an input inside a "subfields" container now looks like:
<input id="textbox1" type="text" name="options_slug[subfields_container][textbox2]" value="">
The idea being that the end user can easily group fields: i.e.,
$options = get_option('options_slug');
foreach($options['subfield_container'] as $subfield) {
// etc...
}
The Problem
As I iterate through these multidimensional arrays, I need to continually update a $options variable at the current index so it can be saved to the DB. So where previously I was able to do:
$id = 'textbox1';
$options[$id] = $_POST['textbox1'];
Now I'm doing something like:
$id = array('subfields_container' => 'textbox2');
$options[$id] = $_POST['textbox2'];
But I get "illegal offset type" errors. Because I can't set an array property using another array.
I've considered just putting dashes in the ID's instead of creating a hierarchical array, something like:
<input id="textbox1" type="text" name="options_slug[subfields_container-textbox2]" value="">
But then I'll lose the ability to foreach over a specific part of the stored options.
The Question
What's the best way to dynamically set a value inside of a multidimensional array when the array is not fixed in structure?
Thank you
I'd suggest to just dynamically create a multi-leveled array:
$arr = array();
$arr['subfields_container']['textbox1'] = $_POST['textbox1'];
print_r($arr);
=>
Array
(
[subfields_container] => Array
(
[textbox1] => <POSTed value>
)
)
All of the non-existent keys will just be created on the fly, regardless of the number of nested levels you specify.
Update
Given that the user can arbitrarily specify any number of nesting levels as elucidated below, you probably want a recursive function that returns the values for all the elements of the current level, and calls itself to retrieve the values for any elements at the current level that contain sub elements.
Example:
function getNestedPostVars($config, $formName, $keys = array()) {
$output = [];
foreach ($config as $label => $fieldConfig) {
if (isset($config['subfields'])) {
$output[$label] = getNestedPostVars(
$config['subfields'],
$formName,
array_merge($keys, array($label))
);
continue;
}
$output[$label] = /* path to $_POST element using $keys/$label */ ;
}
return $output;
}

PHP foreach loop to build multi array

I'm trying to build a multi array with this structure:
Array
(
[2] => Array //this is the user's unique ID
(
[name] => Jack
[location] => Somerville, Massachusetts, United States
[cars] => Array
(
[10] => Toyota //this is the car's unique ID
[11] => Porsche
)
)
[5] => Array
(
[name] => Luke
[location] => Schwelm, North Rhine-Westphalia, Germany
[cars] => Array
(
[1] => Honda
[2] => VW
[5] => Maserati
)
)
[1] => Array
(
[name] => Jabba
[location] => Denver, Colorado, United States
[cars] => Array
(
[3] => Tesla
)
)
)
I am using this foreach loop but am stuck in getting the cars array embedded within the search data array.
Each user may have more than one car so I would need to loop through all cars for each user, generate that array, and put it in the original foreach loop.
$search_data = array();
foreach ($query->result() as $row) {
$search_data[$row->id] = array(
'name' => $row->name,
'location' => $row->location,
'cars' => array($row->car_id), //this is where I need to insert another array
);
}
return $search_data;
Any suggestions how to do this?
Thanks for helping!
SAMPLE TABLE DATA
USER NAME LOCATION CARS
2 JACK A TOYOTA
2 JACK A PORSCHE
5 LUKE B HONDA
5 LUKE B VW
5 LUKE B MASERATI
1 JABBA C TESLA
It seems that you are creating the array through a database table. So can you please give 2 or more sample data. it'll be easier to give an answer if sample data is there.
Edit:
Well this might not be the best code but I think you'll be able to figure out a better way after seeing this
$id = $row['id'];
if (!isset($search_data[$id])){
$search_data[$id] = array();
}
$search_data[$id]['name'] = $row['name'];
$search_data[$id]['location'] = $row['location'];
if (isset($search_data[$id]['cars'])) {
array_push($search_data[$id]['cars'],$row['cars']);
}else{
$search_data[$id]['cars'] = array($row['cars']); //this is where I need to insert another array
}

Categories