I have 3 inputs like this:
<input type="text" name="product[1][name]" >
<input type="text" name="product[1][cost]" >
<input type="text" name="product[1][qty]" >
... which goes until n products
<input type="text" name="product[n][name]" >
<input type="text" name="product[n][cost]" >
<input type="text" name="product[n][qty]" >
and based on the input value a JSON string like this:
{"product[1][name]": "Prod1", "product[1][cost]": "100$", "product[1][qty]": "3", "product[2][name]": "Prod2", ... }
how can I retrieve their name and value because neither json_decode function can take their values because of the array-like name
$decodedObject=json_decode($array['data']); // this data contains the json string
echo $decodedObject->product; // does not work
echo $decodedObject->product[1][qty]; // does not work
is there any simple way?
Or the only way is to cut the name like product[, take the inside elements , and the value after the : and so on?
But how can I even take the object from it without letting PHP know that's not an array ?
Firstly I found an alternative. The problem is that this:
$decodedObject=json_decode($array['data']); // will create an object
will not transform it in an array, instead I have used this:
$decodedObject=json_decode($array['data'], true); // will create an array
after that I had checked how many objects exist, and then just add them to another array:
$i=1;
while(isset($decodedObject["product[$i][qty]"])) // while any element exists
{
$newProducs= array();
$newProducs['name'] = $decodedObject["product[$i][name]"];
$newProducs['cost'] = $decodedObject["product[$i][cost]"];
$newProducs['qty'] = $decodedObject["product[$i][qty]"];
array_push($products, $newProducs); // optional: add to the main array (products) the new-created array (newProducs)
$i++; //increment to search another product
}
The problem was that I was not fully creating an array -_-
While this is not the full answer I still hope somebody will find a better solution and not a change.
Related
I have a hidden input with array:
<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->name.'" />
How do I post the value of this array into the next page?
I tried this method: $a = $_POST['item_name']; but then it gave me the following error:
Array to string conversion in C:\xampp\htdocs\BSSecureTech\payment.php on line 6
Array
Then I tried $a = $_POST['item_name'][0];. It works but then I wouldn't know how many values are in the array. How do I kind of loop the [0] to let it post all the values in the array?
At first i suggest you to change in your HTML like this if your file extension is .php
<input type="hidden" name="item_name[<?=$cart_items?>]" value="<?=$obj->name?>" />
On PHP end check your post array like print_r($_POST);. Then catch your desired value by array index like this
$values = $_POST;
$item = $_POST['item_name']['your index'];
echo $item;
I know there are some similar questions but none of them solves my issue.
I have a simple form:
<form method="post">
Import data: <textarea type="text" name="import"></textarea>
<input type="submit">
</form>
Then I get data from the "import" field:
$current = my_data();
$import = $_POST['import'];
$merge = array_merge($current,$import);
The problem is, even if I paste:
array('foo' => 'bar')
I get:
Warning: array_merge(): Argument #2 is not an array in
(address)
on line (line)
I can't change the HTML markup and I have to paste arrays there. Any ideas how to fix it? I've been reading about serialize() but not sure if there's anything to serialize is array() is not array() for PHP. Why is that? Any solutions? Thanks a lot!
UPDATE
$current hold an array of options for my theme.
$merge is supposed to hold the same keys with different values (around 30-50 of them, not multidimensional but might be in the future), but of course users might add new ones so in order to ignore them I'm actually using:
$imported_options = array_merge($current_options , array_intersect_key($_POST["import"], $current_options ));
(simplified this one as it's just an example)
So after all I want to load an array from the form and update the other array with it.
PHP will not create arrays in $_GET/$_POST unless you tell it to:
Import data: <textarea type="text" name="import[]"></textarea>
^^---- need these
Without the [], PHP will treat any duplicate field names as strings to be overwritten. With [] in the name, PHP will treat them as new elements in an array.
You can do
$current['import'] = $import;
Or you can change your html this way:
<textarea type="text" name="myarray['import']"></textarea>
And in php:
$import = $_POST['myarray'];
The second argument is not an array.
$_POST['import'] = value received from the form.
With that said, try:
$current [] = $_POST['import'];
What are you trying to get from $_POST['import'] ?
you are using a textarea to get an array?
if it's just a single variable then use array_push
http://php.net/manual/es/function.array-push.php
for array_merge you need to have 2 arrays.
I would like to perform massive content replace for some data called from mysql db in a php file.
Firstly, I have prepared an replacement array for content replace:-
$replacement_array = array(
"###123###" => "hello",
"###456###" => "great",
"###789###" => "ok"
);
Secondly, I call data from mysql db, the data would look like this:-
$data = "<input type="text" name="field1" value="###123###"><input type="text" name="field2" value="###789###">";
Thirdly, refer to the array, check up if $data contains any matched value in $replacement_array (this is the black box I wish to consult).
Fourthly, after content replacement, the resulting $data would become this:-
$data = "<input type="text" name="field1" value="hello"><input type="text" name="field2" value="ok">";
I guess the above will involve php in_array(), str_replace() and preg_match(), and I guess the flow may be like this:-
1) use explode() function to chop $data into a new $data_array by ###;
2) check values in $data_array is in_array() of $replacement_array;
3) if in_array(), carry out str_replace(); (in the above example there will be 2 times)
4) $data has proceeded 2 times of content replace, and ready to be used.
if the above steps 3) and 4) are carried out step by step, I it will be easy, however, if I wish to do it in 1 time, how shall I handle it?
You can use str_replace with first parameter as search array and second parameter as replace array.
$arr = array("###123###","###456###","###789###");
$arr1 = array("hello","great","ok");
str_replace($arr,$arr1, $data);
This question already has answers here:
How do I Sort a Multidimensional Array in PHP [duplicate]
(10 answers)
Closed 9 years ago.
I have a form where I'm creating a number of item arrays:
<input type="hidden" value="Full/Double Mattress" name="pickup1-dropoff1Items[1][0]">
<input type="text" name="pickup1-dropoff1Items[1][1]">
<input type="hidden" value="20" name="pickup1-dropoff1Items[1][2]">
<input type="hidden" value="FMat" name="pickup1-dropoff1Items[1][3]">
<input type="hidden" value="1" name="pickup1-dropoff1Items[1][4]">
so the structure is basically:
array(
array('title', quantity, price, 'shorthand', order),
array('title', quantity, price, 'shorthand', order)
)
etc...
I'm getting this information using PHP and sending it in an email. I can get one of these arrays like so:
$pickup1_dropoff1Items = $_POST['pickup1-dropoff1Items'];
I would like to sort the arrays in $pickup1_dropoff1Items by the 'order' number (i.e. index #4, i.e. $pickup1-dropoff1Items[i][4]) in each of those arrays.
Can this be done using PHP ksort()? Does anyone have any idea how to sort an array like this using PHP?
Thanks!
It's not tested but I think this will do what you need:
// first create a new array of just the order numbers
// in the same order as the original array
$orders_index = array();
foreach( $pickup1_dropoff1Items as $item ) {
$orders_index[] = $item[4];
}
// then use a sort of the orders array to sort the original
// array at the same time (without needing to look at the
// contents of the original)
array_multisort( $orders_index, $pickup1_dropoff1Items );
This is essentially example 1 here:
http://www.php.net/manual/en/function.array-multisort.php
but our $ar2 is an array of arrays instead of an array of single values. Also if you need more control over the sort you'll see examples of options you can use at that URL: just add them to the list of arguments for array_multisort.
For sorting complex arrays like this, you can use something like usort() which "sorts an array by values using a user-defined comparison function".
See the example on php.net for more information.
how to send array through url in PHP?
I have an array of product ids i want to use these id through url because this is the osCommerce needs it in which i am working in, how can i do it?
Generally osCommerce asks for the single product insertion which in turn gives me back a product id which i pass into the url and get it in shopping cart where i am shown this added product, but now i have multiple products added in first page with different generated product ids and i have to display these products the same way they are displayed in genaral, for which i will need all these generated ids here in url
Your looking for http_build_query().
Example from php.net:
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data);
// foo=bar&baz=boom&cow=milk&php=hypertext+processor
echo http_build_query($data, '', '&');
// foo=bar&baz=boom&cow=milk&php=hypertext+processor
?arr[]=abc&arr[]=pqr&arr[]=xyz&arr[]=xxx
well what i would do is json_encode(php json) the array and assign that to a variable in php. you can then urlencode the variable to send it via the url. On the other end you can json_decode. Do look up for json if you are not aware of it. its very powerful and useful though.
You can either serialize() it or send it as ?a[]=1&a[]=val2&someOtherArg=val. This will give a $_GET array like:
array(
'a' => array(
0 => '1',
1 => 'val2',
),
'someOtherArg' => 'val'
)
Do note, however, that you should probably keep your entire query below ~2k characters. (more)
If you are POST-ing data, then name your fields with PHP array-style syntax:
<input type="text" name="myArray[]" value="A">
<input type="text" name="myArray[]" value="B">
<input type="text" name="myArray[]" value="C">
If you want to pass the data in a GET request, you can separate the data and split it server side using explode:
page.php?myData=A,B,C,D
...
$myArray = explode(',', $_POST['myData']);
It should be sufficient to encode them like this:
http://your.url/page.php?myArray[0]=val1&myArray[1]=val2
If you already have the product IDs in an array, then you can use the http_build_query() function, which will encode the array like thus:
http://www.example.com/?pid[]=1&pid[]=2&pid[]=3 ...
Hope that helps.