Working with opencart and am trying to enter another value within the product session. By default it only brings ID. How can I get further information?
if (!in_array($this->request->post['product_id'], $this->session->data['wishlist'])) {
$this->session->data['wishlist'][] = $this->request->post['product_id'];
$this->session->data['wishlist'][] = $my_var;
}
If I read this correctly you are trying to add additional data to an already existing array...what you are looking for is
array_push();
array_push — Push one or more elements onto the end of array
syntax:
int array_push ( array &$array , mixed $value1 [, mixed $... ] )
example:
$array = array();
$addingthistoarray = "value to add";
array_push($array, $addingthistoarray);
I'm not sure exactly what you're looking for, but you should be able to do something like this (assuming your "$_SESSION"):
PHP session array
session_start();
$_SESSION['wishlist'] = array( ... );
...
$_SESSION['wishlist']['product_id'] = $this->request->post['product_id'];
...
Related
I try to write a string into a variable in between an array
if ($row_klasse['RabKlNummerVK'] != ''){
$headerrabklasse = '\'Rabatt\'\=\>\'price\'\,';
}
else {$headerrabklasse = '';}
then I want to write the variable $headerrabklasse in:
$writer = new XLSXWriter();
$writer->writeSheetHeader (Preisliste, array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
$headerrabklasse
'Nettopreis'=>'price3',
'UVP'=>'price'),
['auto_filter'=>true, 'widths'=>[20,50,15,45,15,8,8,8,8,8],
'font-style'=>'bold', 'fill'=>'#eee',
'freeze_rows'=>1,
'freeze_columns'=>0] );
And I always get an error...
HAs anybody an idea?
In PHP you can easily append data to array like this:
//Define array with default values
//BTW: if you work with PHP >= 5.4 better to use [] instead of array()
$sheetHeaders = array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
'Nettopreis'=>'price3',
'UVP'=>'price'
);
if ($row_klasse['RabKlNummerVK'] != ''){
//Here you append data to existing array in format: array[key] = value
$sheetHeaders['Rabatt'] = 'price';
}
//Then use fulfilled array as you want
$writer->writeSheetHeader ($preisliste, $sheetHeaders);
Your array takes keys and values, so you need to write a key name, and pass the variable as a value. I also noticed you were mixing Array declarations. In PHP you can call an array like this:
Array(el1, el2, ...)
or like this:
[el1, el1, ...]
Either one is fine, but for best practices you want to pick one and stick with it.
$writer->writeSheetHeader(Preisliste, [
'Marke'=>'string',
...
'MyNewKeyName' => $headerrabklasse,
...
],
[
...
]
);
I guess you wan't to do this one:
if ($row_klasse['RabKlNummerVK'] != '') {
$headerrabklasse = ['Rabatt' => 'price'];
}
else {$headerrabklasse = [];}
You could do stuff like that:
$writer->writeSheetHeader (Preisliste, array_merge(array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
'Nettopreis'=>'price3',
'UVP'=>'price'),
['auto_filter'=>true, 'widths'=>[20,50,15,45,15,8,8,8,8,8],
'font-style'=>'bold', 'fill'=>'#eee',
'freeze_rows'=>1,
'freeze_columns'=>0]), $headerrabklasse);
So I wrote a class that can parse XML documents and create SQL queries from it to update or insert new rows depending on the settings.
Because the script has to work with any amount of nested blocks, the array that I'm putting all the values in has its path dynamically created much like the following example:
$path = array('field1','field2');
$path = "['".implode("']['",$path)."']";
eval("\$array".$path."['value'] = 'test';");
Basically $path contains an array that shows how deep in the array we currently are, if $path contains for instance the values main_table and field I want set $array['main_table']['field']['value'] to 'test'
As you can see I am currently using eval to do this, and this works fine. I am just wondering if there is a way to do this without using eval.
Something like
$array{$path}['value'] = 'test'; but then something that actually works.
Any suggestions?
EDIT
The reason I'm looking for an alternative is because I think eval is bad practice.
SECOND EDIT
Changed actual code to dummy code because it was causing a lot of misunderstandings.
Use something like this:
/**
* Sets an element of a multidimensional array from an array containing
* the keys for each dimension.
*
* #param array &$array The array to manipulate
* #param array $path An array containing keys for each dimension
* #param mixed $value The value that is assigned to the element
*/
function set_recursive(&$array, $path, $value)
{
$key = array_shift($path);
if (empty($path)) {
$array[$key] = $value;
} else {
if (!isset($array[$key]) || !is_array($array[$key])) {
$array[$key] = array();
}
set_recursive($array[$key], $path, $value);
}
}
You can bypass the whole counter business with the array append operator:
$some_array[] = 1; // pushes '1' onto the end of the array
As for the whole path business, I'm assuming that's basically an oddball representation of an xpath-like route through your xml document... any reason you can't simply use that string as an array key itself?
$this->BLOCKS['/path/to/the/node/you're/working/on][] = array('name' => $name, 'target' => $target);
You can use a foreach with variable variables.
// assuming a base called $array, and the path as in your example:
$path = array('field1','field2');
$$path = $array;
foreach ($path as $v) $$path = $$path[$v];
$$path['value'] = 'test';
Short, simple, and much better than eval.
I am recently facing a practical problem.I am working with ajax form submission and there has been some checkboxes.I need all checkboxes with same name as key value pair.Suppose there is 4 checkboxes having name attribute =checks so i want something like $arr['checks'] = array(value1, value2, ...)
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
I am using below code to make into an array
public function smdv_process_option_data(){
$dataarray = array();
$newdataarray = array();
$new = array();
$notices = array();
$data = $_POST['options']; // data received by ajax
$dataarray = explode('&', $data);
foreach ($dataarray as $key => $value) {
$i = explode('=', $value);
$j = 1;
if(array_key_exists($i[0], $newdataarray)){
if( !is_array($newdataarray[$i[0]]) ){
array_push($new, $newdataarray[$i[0]]);
}else{
array_push($new, $i[1]);
}
$newdataarray[$i[0]] = $new;
}else{
$newdataarray[$i[0]] = $i[1];
}
}
die($newdataarray);
}
Here i want $newdataarray as like below
array(
'name' => 'alex',
'checks => array(code1, code2, code3),
)
But any how I am missing 2nd value from checks key array.
As I see it you only need to do two explode syntaxes.
The first on is to get the name and here I explode on & and then on name= in order to isolate the name in the string.
The checks is an explode of &checks= if you omit the first item with array_slice.
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$name = explode("name=", explode("&", $str)[0])[1];
// alex
$checks = array_slice(explode("&checks=", $str), 1);
// ["code1","code2","code3"]
https://3v4l.org/TefuG
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
Use parse_str instead.
https://php.net/manual/en/function.parse-str.php
parse_str ( string $encoded_string [, array &$result ] ) : void
Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).
$s = 'name=alex&checks=code1&checks=code2&checks=code3';
parse_str($s, $r);
print_r($r);
Output
Array
(
[name] => alex
[checks] => code3
)
You may think this is wrong because there is only one checks but technically the string is incorrect.
Sandbox
You shouldn't have to post process this data if it's sent correctly, as that is not included in the question, I can only make assumptions about it's origin.
If your manually creating it, I would suggest using serialize() on the form element for the data for AJAX. Post processing this is just a band-aid and adds unnecessary complexity.
If it's from a source outside your control, you'll have to parse it manually (as you attempted).
For example the correct way that string is encoded is this:
name=alex&checks[]=code1&checks[]=code2&checks[]=code3
Which when used with the above code produces the desired output.
Array
(
[name] => alex
[checks] => Array
(
[0] => code1
[1] => code2
[2] => code3
)
)
So is the problem here, or in the way it's constructed...
UPDATE
I felt obligated to give you the manual parsing option:
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$res = [];
foreach(explode('&',$str) as $value){
//PHP 7 array destructuring
[$key,$value] = explode('=', $value);
//PHP 5.x list()
//list($key,$value) = explode('=', $value);
if(isset($res[$key])){
if(!is_array($res[$key])){
//convert single values to array
$res[$key] = [$res[$key]];
}
$res[$key][] = $value;
}else{
$res[$key] = $value;
}
}
print_r($res);
Sandbox
The above code is not specific to your keys, which is a good thing. And should handle any string formatted this way. If you do have the proper array format mixed in with this format you can add a bit of additional code to handle that, but it can become quite a challenge to handle all the use cases of key[] For example these are all valid:
key[]=value&key[]=value //[key => [value,value]]
key[foo]=value&key[bar]=value //[key => [foo=>value,bar=>value]]
key[foo][]=value&key[bar][]=value&key[bar][]=value //[key => [foo=>[value]], [bar=>[value,value]]]
As you can see that can get out of hand real quick, so I hesitate to try to accommodate that if you don't need it.
Cheers!
My php variable $ex_product_ids which contain value 18,63,72,91 & I have checked it using echo $ex_product_ids it show the value of my input field of my plugin correctly but when I want to use it in a array like $target_products = array($ex_product_ids); its not working only return result for the first array item.
here is the code not working
$_options = get_option( 'license_page_option' );
$ex_product_ids = $_options['ex_product_ids_warranty']; // it have value 18,63,72,91
$target_products = array($ex_product_ids);
but if I manually use those ids like $target_products = array(18,63,72,91); it works
I'm sorry if i'm doing anything wrong ! please help
I think you need to use explode() because current value can be the simple string and you need to convert it to an array of values.
$_options = get_option( 'license_page_option' );
$ex_product_ids = $_options['ex_product_ids_warranty']; // it have value 18,63,72,91
$target_products = explode(",",$ex_product_ids);
print_r($target_products); // array(18,63,72,91)
I know this should be very simple, but boy I'm making a mess of it... would be great if someone could point me in the right direction.
I've got an array which looks like this:
print_r($request_attributes['length']);
Array
(
[0] => 28.00000
[1] => 18.00000
)
and am trying to modify like so:
if(is_array($request_attributes['length'])) {
$request_attributes['length'] = $request_attributes['length'][0];
print($request_attributes['length']);
$request_attributes['length'] = $request_attributes['length'][1];
print($request_attributes['length']);
}
which gives the correct output in the first update, but the second item outputs an '8'. I've tried the above in both a for and foreach which results in similar output for both this and the other two arrays ( width(8) and height(0) - they should result in 18.00000 and 13.00000 respectively ). So I guess I really have two questions:
1. How do I update this(these) element(s)?
2. Where are the funny outputs actually coming from?
If anyone can help, I'd really appreciated it.
Just have a look at this. Your problem is, that you override you variable and in the second step $request_attributes['length'] is a string. Just define another var for your values.
$request_attributes['length'] = [
28.000,
18.000
];
$attributes = array();
if (is_array($request_attributes['length'])) {
foreach ($request_attributes['length'] as $value) {
$attributes[] = $value;
}
}
As you see $attributes will contain all values of your $request_attributes['length'] array and will not be overwritten.
Define araay as below
$val=array([0]=>"18.000",[1]=>13.000)
then use
if(is_array($request_attributes['length'])) {
$request_attributes['length'] = $val;
print_r($request_attributes['length']);
$request_attributes['length'] = $val;
print_r($request_attributes['length']);
}
Previously your array doesnt have any name.
Your print will only return Just array not the values
use
print_r($request_attributes['length']) ;
instead