Here is a var_dump or an array returned from my MODEL:
array (size=5)
0 =>
array (size=3)
0 =>
object(stdClass)[19]
public 'X_SIZE' => string '1.75x3' (length=6)
1 =>
object(stdClass)[20]
public 'X_SIZE' => string '1.75x3.5(slim)' (length=14)
2 =>
object(stdClass)[21]
public 'X_SIZE' => string '2x3' (length=3)
1 =>
array (size=3)
0 =>
object(stdClass)[17]
public 'X_PAPER' => string '14ptGlossCoatedCoverwithUV(C2S)' (length=31)
1 =>
object(stdClass)[18]
public 'X_PAPER' => string '14ptPremiumUncoatedCover' (length=24)
2 =>
object(stdClass)[24]
public 'X_PAPER' => string '16ptDullCoverwithMatteFinish' (length=28)
2 =>
array (size=2)
0 =>
object(stdClass)[23]
public 'X_COLOR' => string '1000' (length=4)
1 =>
object(stdClass)[22]
public 'X_COLOR' => string '1002' (length=4)
3 =>
array (size=4)
0 =>
object(stdClass)[26]
public 'X_QTY' => string '100' (length=3)
1 =>
object(stdClass)[25]
public 'X_QTY' => string '250' (length=3)
2 =>
object(stdClass)[29]
public 'X_QTY' => string '500' (length=3)
3 =>
object(stdClass)[30]
public 'X_QTY' => string '1000' (length=4)
4 =>
array (size=3)
0 =>
object(stdClass)[28]
public 'O_RC' => string 'YES' (length=3)
1 =>
object(stdClass)[27]
public 'O_RC' => string 'NO' (length=2)
2 =>
object(stdClass)[33]
public 'O_RC' => string 'NA' (length=2)
My controller is sending to my view and on my view the above dump is of: var_dump($printerOptions)
Ok so I need to create a dropdown menu for each of these arrays and radio buttons for the O_RC array.
I am using codeigniter and using form_dropdown('',$val); inside of a foreach loop causes multiple dropdowns for each key and element in the array.
foreach ($printerOptions as $Options)
{
//var_dump($Options);
foreach ($Options as $Specs)
{
echo $Specs->X_SIZE;
echo $Specs->X_PAPER;
echo $Specs->X_COLOR;
echo $Specs->X_QTY;
echo $Specs->O_RC;
}
}
This ^ code will echo out the expected values of the corresponding arrays but for some reason I get LOOPING errors with the output:
Undefined property: stdClass::$X_PAPER
Undefined property: stdClass::$X_COLOR
Undefined property: stdClass::$X_QTY
Undefined property: stdClass::$O_RC
Looking at my array how can I create a dropdown menu for each of the arrays respectively?
Thanks for the help.
MODEL /// Update ///
class M_Pricing extends CI_Model {
function get_prices()
{
$table_by_product = 'printer_businesscards'; //replace with URI Segment
//Get all the columns in the table set by the page URI of $table_by_product variable
$get_all_col_names = $this->db->list_fields($table_by_product);
//Loop through the column names. All names starting with 'O_' are optional fields for the
//current product. Get all Distinct values and create a radio button list in form.
$resultArray = array();
foreach ($get_all_col_names as $key => $value) {
//get all o_types for the product by column name
if (preg_match('/O_/', $value))
{
$v = (array('Specs' => $value));
foreach ($v as $vals) {
$this->db->select($vals);
$this->db->distinct();
$qX = $this->db->get($table_by_product);
$resultArray[] = $qX->result();
}
}
//Get all x_types for the product by column name. All 'X_' types are specific product options.
//Create a dropdown menu with all DISTINCT product options.
if (preg_match('/X_/', $value))
{
$v = (array('Type' => $value));
foreach ($v as $vals) {
$this->db->select($vals);
$this->db->distinct();
$qX = $this->db->get($table_by_product);
$resultArray[] = $qX->result();
}
}
}
//return $resultArray
//var_dump($resultArray); die;
return $resultArray;
}
As i understand your result array should be object or hash and look like:
array('Type'=>array(
'X_SIZE'=>array('1.75x3','1.75x3.5(slim)','2x3'),
'X_PAPER'=>array('14ptGlossCoatedCoverwithUV(C2S)','14ptPremiumUncoatedCover'),
///...),
'Specs'=>array(
//...)
);
to loop through such structure:
//Types
echo 'Types';
foreach ($Options['Types'] as $type=>$values) {
echo $type;
echo "<select>";
foreach ($values as $value) {
echo "<option value="$value">$value</option>";
}
echo "</select>";
}
//Specs
echo 'Specs';
foreach ($Options['Specs'] as $type=>$values) {
echo $type;
echo "<select>";
foreach ($values as $value) {
echo "<option value="$value">$value</option>";
}
echo "</select>";
}
model:
<?php
class M_Pricing extends CI_Model {
function get_prices()
{
$table_by_product = 'printer_businesscards'; //replace with URI Segment
//Get all the columns in the table set by the page URI of $table_by_product variable
$get_all_col_names = $this->db->list_fields($table_by_product);
//Loop through the column names. All names starting with 'O_' are optional fields for the
//current product. Get all Distinct values and create a radio button list in form.
$resultArray=array();
$resultArray['Options']=array();
$resultArray['Specs']=array();
foreach ($get_all_col_names as $key => $value) {
//get all o_types for the product by column name
$opt_type="";
if (preg_match('/O_/', $value)) {$opt_type="Options";} elseif
(preg_match('/X_/', $value)) {$opt_type="Specs";} else {continue;}
if (!isset($resultArray[$opt_type][$value])) {$resultArray[$opt_type][$value]=array();}
$this->db->select($value);
$this->db->distinct();
$qX = $this->db->get($table_by_product);
foreach ($qX->result() as $v) {
$resultArray[$opt_type][$value][]=$v->$value;
}
}
//return $resultArray
//var_dump($resultArray); die;
return $resultArray;
}
}
Related
I have an array of associative array, I will like to update the values in this array, hence I created a function that looks like this.
//The Array of Associative arrays
array (size=2)
0 =>
array (size=3)
'slang' => string 'Tight' (length=5)
'description' => string 'Means well done' (length=15)
'example-sentence' => string 'Prosper it Tight on that job' (length=28)
1 =>
array (size=3)
'slang' => string 'Sleet' (length=5)
'description' => string 'Means to send on long errand' (length=28)
'example-sentence' => string 'I am going to sleep sia' (length=23)
//The function
public function update($slang, $new)
{
array_map(function($data, $key) use($slang, $new)
{
if($data['slang'] == $slang)
{
$data[$key] = array_replace($data, $new);
}
}, UrbanWord::$data);
}
I tired running this but the original array will not update. I need help on how to go about fixing this please.
Thanks
You may use array_reduce instead of array_map as following:
public function update($array, $slang, $new)
{
return array_reduce($array, function ($result, $item) use ($slang, $new) {
if ($item['slang'] == $slang) {
$item = array_replace($item, $new);
}
$result[] = $item;
return $result;
}, array());
}
Usage:
UrbanWord::$data = $this->update(
UrbanWord::$data,
'Tight',
array('description' => 'another description')
);
var_dump($myUpdatedArray);
If you want to update it directly passing the UrbanWord::$data by reference you may try something like:
class UrbanWord
{
public static $data = array(
array(
'slang' => 'Test',
'Desc' => 'Frist Desc'
),
array(
'slang' => 'Test1',
'Desc' => 'Second Desc'
)
);
}
class MyClass
{
public function update(&$array, $slang, $new)
{
$array = array_reduce($array, function ($result, $item) use ($slang, $new) {
if ($item['slang'] == $slang) {
$item = array_replace($item, $new);
}
$result[] = $item;
return $result;
}, array());
}
}
$myClass = new MyClass();
$myClass->update(UrbanWord::$data, 'Test', array('Desc' => 'test'));
echo '<pre>';
var_dump(UrbanWord::$data);
echo '</pre>';
I spent over 2 hours looking for the solution, and I leave it to you because I am completely blocked. I try to learn the object in PHP. I created a function that return me the result of an SQL query.
Here is the var_dump return :
object(stdClass)[6]
public 'name' =>
array (size=2)
0 =>
object(stdClass)[11]
public 'id' => string '1' (length=1)
1 =>
object(stdClass)[12]
public 'id' => string '5' (length=1)
I used a foreach to parse this, but I don't get directly the id of each element. And I especially don't want to use another foreach.
foreach($function as $key => $value){
var_dump($value->id);
}
But it doesn't work there.
Here is the function called who returns this result
public function nameFunction () {
$obj = new stdClass();
$return = array();
$request = $this->getConnexion()->prepare('SELECT id FROM table') or die(mysqli_error($this->getConnexion()));
$request->execute();
$request->store_result();
$request->bind_result($id);
while ($request->fetch()) {
$return[] = parent::parentFunction($id);
}
$obj->name = $return;
$request-> close();
return $obj;
}
And parent::parentFunction($id) returns :
object(stdClass)[11]
public 'id' => string '1' (length=1)
You are looping the object instead of array. Try to use this code
foreach($function->name as $key => $value){
var_dump($value->id);
}
Tell me if it works for you
This question might help you :
php parsing multidimensional stdclass object with arrays
Especially answer from stasgrin
function loop($input)
{
foreach ($input as $value)
{
if (is_array($value) || is_object($value))
loop($value);
else
{
//store data
echo $value;
}
}
}
Possibly already been asked but I can't seem to find the answer I'm looking for.
How can I check that a variable is in an array?
Here is my code so far - ideally I wan't to echo out something when the ProductID also exists in the lastUpdatedProduct array as well as the productOptions array.
<?php if ($this->productOptions) { ?>
<?php foreach ($this->productOptions as $options) {
$array = $this->lastUpdatedProduct;
echo '<strong>' . $options['ProductID'] . '</strong>';
if(in_array($options['CentreID'], $array)) {
echo 'it exists';
}
}
}?>
Heres my array:
array
0 =>
array
'pid' => string '391' (length=3)
1 =>
array
'pid' => string '467' (length=3)
2 =>
array
'pid' => string '474' (length=3)
3 =>
array
'pid' => string '2985' (length=4)
4 =>
array
'pid' => string '2985' (length=4)
5 =>
array
'pid' => string '424' (length=3)
The problem is that $array is an array with arrays and you are trying to find something inside one of the inner arrays. Try with this:
foreach ($array as $entry) {
if (is_array($entry) && in_array($options['CentreID'], $entry))
echo 'it exists';
}
Ideally I wan't to echo out something when the ProductID is in the array
if(is_array($options['ProductID'])) { }
Live Preview
Edit
Ideally I wan't to echo out something when the ProductID also exists in the lastUpdatedProduct array as well as the productOptions array.
if(is_array($this->productOptions)) {
foreach($array as $pid) {
if(in_array($pid, $options['ProductID'])) {
//echo
}
}
}
I have a POST request array that looks like this
$request = array (size=2)
'licence' => string 'uDyQwFwqV7aQG2z' (length=15)
'user' =>
array (size=7)
'first_name' => string 'Danut' (length=5)
'last_name' => string 'Florian' (length=7)
'username' => string 'daniesy9' (length=8)
'password' => string '123456' (length=6)
'rpassword' => string '123456' (length=6)
'email' => string 'daniesy+1#me.com' (length=16)
'phone' => string '9903131' (length=7)
This in fact is an array which represents values sent by a form. I know the name of the elements, for example the username input has the name of user[username] and i have to find the related value from the array, by name. Something like:
$key = "user[username]";
$request[key];
Any idea how to do this?
I know that the correct way to do it is $request["user"]["username"] but it's quite complicated because i have to use the fields names from the form which are user[username], user[firstname], etc and it might have up to 4 levels of depth.
Answered in comments but similar Question to
Convert a String to Variable
eval('$username = $request["user"]["username"];');
Edit
Eval not a valid suggestion as request data.
So I would suggest the second method on this post
<?php
$request = array(
'user' => array(
'username' => 'joe_blogs'
)
);
function extract_data($string) {
global $request;
$found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches);
if (!$found_matches) {
return null;
}
$current_data = $request;
foreach ($matches[1] as $name) {
if (key_exists($name, $current_data)) {
$current_data = $current_data[$name];
} else {
return null;
}
}
return $current_data;
}
$username = extract_data('request["user"]["username"]');
?>
function findInDepth($keys, $array){
$key = array_shift($keys);
if(!isset($array[$key])){
return FALSE;
}
if(is_array($array[$key])){
return findInDepth($keys, $array[$key]);
}
return $array[$key];
}
$key = "user[username]";
$keys = preg_split("/(\[|\])/", $key);
echo findInDepth($keys, $request);
This function solves my problem. It first splits the string (aka the input name) into an array of keys and then recessively searches in depth the array by keys until it finds a value which is not an array and returns FALSE otherwise.
You could separate keys with dots. Primitive example:
<?php
class ArrayDot
{
protected $array = [];
public function __construct(array $array) {$this->array = $array;}
public function get($path)
{
$array = $this->array;
foreach(explode('.', $path) as $key) {
$array = $array[$key];
}
return $array;
}
}
$array = [
'user' => [
'username' => 'tootski',
]
];
$a = new ArrayDot($array);
echo $a->get('user.username'); # tootski
I have several values stored in $_SESSION beginning with 'first_name_' & 'last_name_' which then a number appended to the end deepening on how many names are generated.
I am able to extract each of these values from the session and add to an array but would like to pair up the first and last names together within a nested array. (if that makes sense)
at the moment I have:
$users_array = array();
foreach ($_SESSION as $key => $value) {
if(strpos($key, 'first_name_') === 0) {
$users_array[] = $value;
}
if(strpos($key, 'last_name_') === 0) {
$users_array[] = $value;
}
}
This produces an output with var_dump:
array
0 => string 'John' (length=4)
1 => string 'Smith' (length=8)
2 => string 'Jane' (length=4)
3 => string 'Doe' (length=3)
But what I would like is something like:
array
'user' =>
array
'first_name' => string 'John' (length=4)
'last_name' => string 'Smith' (length=5)
array
'first_name' => string 'Jane' (length=4)
'last_name' => string 'Doe' (length=5)
Any suggestions on how I can achieve this?
deceze is right in his comment... But just so people with similar issues with creating 2-dimensional array from a 1-dimensional array, here is a solution. Also, note that PHP does not guarantee that the order will be same when iterating using FOREACH. As this will work, it is still prone to errors.
$users_array = array();
foreach ($_SESSION as $key => $value) {
if(strpos($key, 'first_name_') === 0) {
$users_array[] = array();
$users_array[count($users_array)-1]['first_name'] = $value;
}
if(strpos($key, 'last_name_') === 0) {
$users_array[count($users_array)-1]['last_name'] = $value;
}
}