I passing an array from Jquery(post) to php like:
[["a","b","c"],["aa:","bb","cc"]]
How to extract this array in php?
My code is:
UPDATE
$data = json_decode($_POST['data']);
print_r($data);
This code return :
Array
(
[0] => Array
(
[0] => as
[1] => as
[2] =>
)
[1] => Array
(
[0] => asas :
[1] => as
[2] => text
)
)
Instead of passing an array. You can tackle this two different ways
1) encode everything in JSON and pass it to php.
2) take everything that you need from the form and serialize it. Then explode the serialized data in your language of choice.
Passing arrays will not work the way you think it will. So it's best to just serialize the data and then do what you need. Using loops is a waste of time and CPU resources that could slow down the users experience.
Related
I use ngx-translate to translate keyword through my app, including a list of tags. User should be able to search through them in any language.
Previously I was doing
this.tag_array_filtered = this.tag_array.filter(tag =>
tag.toUpperCase().includes(this.tag_searched.toUpperCase()));
)
but it only search the key word, not through translations.
this is how I get a translation from a key
this.translate.get(tag).subscribe(value => {
console.log(value);
})
the variable tag_arrayis an array of key, ready to be translated. tag_searched contain the user input. tag_array_filtered is the array of key (not translated) to be displayed
What I want to do: (not working obviously)
this.tag_array_filtered = this.tag_array.filter(tag =>
this.translate.get(tag.toUpperCase()).subscribe((value: string) => {
value.includes(this.tag_searched.toUpperCase())
})
)
How can I filter my array while transforming the value with a subscribe ? I want to compare each value translated from the array to the user input.
I could do it with hand-made loops I guess but if there is a solution already existing it would probably be much faster.
The translate.get() method also accepts an array of strings.
You could try like this. The final output will be an object which you could transform it into an array if needed.
let tag_array_filtered = this.tag_array.filter(tag =>
tag.toUpperCase()
.includes(this.tag_searched.toUpperCase())
.map(e => e.toUpperCase())
this.translate.get(matching_tags).subscribe((values: {}) => {
this.tag_array_filtered_object = values
})
This question already has answers here:
INSERT array - PDO
(2 answers)
Binding values from arrays?
(3 answers)
Closed 5 years ago.
I have tried both the links but I don't get the expected variables content in $fields and $newdata
** This question has developed in a new one here **
PHP how to extract keys names and values from associative array for mysql query (as explained I'm newbie and it took some work to get the question asked in the right way)
so I kindly print here some var_dump and cast to kindly ask your support.
For simplicity in my learning experiment, I'm working with a dummy table of just 5 fields, as you see they are: selected, user_id, user_name, user_company and user_email.
Finally I have inserted just 2 rows of values.
Using this code
$Arr = (array)$data;
print_r ( $Arr );
I can see this output
Array (
[0] => Array ( [selected] => [user_id] => 3 [user_name] => nome3 [user_company] => azien3 [user_email] => email3 )
[1] => Array ( [selected] => 1 [user_id] => 6 [user_name] => nome6 [user_company] => azien6 [user_email] => email6 )
)
next I try to apply the code of your links
24 $fields = implode(",", array_keys($Arr));
25 $newdata = "'" . implode("','", $Arr) . "'";
26
27 var_dump($fields);
28 echo "<br><br>";
29 var_dump($newdata);
But something is wrong in my interpreteation or in my code , because the output is
Notice: Array to string conversion in D:\xampp\htdocs\ajax-json\post.php on line 25
Notice: Array to string conversion in D:\xampp\htdocs\ajax-json\post.php on line 25
string(3) "0,1"
string(15) "'Array','Array'"
can you kindly point out what's wrong?
e.g. is my array properly formed?
ORIGINAL QUESTION
I'm newbie and after further readings I got the point and hopefully now my question could result more simple. Thank you for any hint.
I have a bidimensional array since its records are coming from an html table.
The collection made on the html side generates an associative array so each row is like in the following example where, also, you can see, the keys are many
[item] => Array (
[0] => Array (
[unit] => "car"
[qty] => 3
[description] => "Description 1"
....
[key47] => "thin"
)
[1] => Array (
[unit] => "bike"
[qty] => 74
[description] => "Description 2"
....
[key47] => "large"
)
)
The mysql table name where I want to insert the items is named items_table
"unit" "qty" and "description" and all the remaining keys (total 47) are exactly the same names of the items_table columns
When on the php side I'd like to have a sort of automatic query generation maybe with PDO that would pick the columns names from the inner array keys names and will insert the corresponding key value in the correct column.
The goal is to avoid creating such a awkward and extremely long query.
Preferred method would be with PDO, avoid binding 47 keys.
This sort of automatism is also useful because in the future columns in the mysql table may being added and or removed and or renamed, so I'd like to forget about the query thinking only about properly editing the html table (on that side the array is already automatically generated with some javascript)
Do you think is possible to do this?
If yes how to?
Does this still need some foreach loop?
Thank you for helping
E.g.:
core_table
id* unit quantity description
1 car 3 Description 1
2 bike 74 Description 2
adjunct_table
core_id* meta_key* meta_value
1 47 Description of key n.47 first row
2 47 Description of key n.47 second row
* = (component of) PRIMARY KEY
I have an array of arrays in PHP that I need to send to javascript as JSON. The PHP script and AJAX call work, but the returned JSON string is not parse-able JSON; instead of an array of arrays, it just sticks the arrays together with no separators or container.
Example JSON String:
[{"id":"77","options":[],"price":"4.25","title":"Zeppoli's","spec":""}][{"id":"78","options":[],"price":"7.95","title":"Battered Mushrooms","spec":""}]
PHP Snippet that creates above JSON String:
$cartArr = array(); // array of objects to be jsonified
foreach($products as $product){
unset($newItem);
$newItem = array(
"id" => $product['itemID'],
"options" => $theseOptions,
"price" => $product['price'],
"title" => $product['name'],
"spec" => $product["special"],
"cartid" => $product['ID']
);
array_push($cartArr,$newItem);
echo json_encode($cartArr);
}
An attempt to JSON.parse() the string will result in the following error, unless the string is manually corrected.
Uncaught SyntaxError: Unexpected token [
You're building json in a loop, which means you're outputting MULTIPLE independent json strings, which is illegal syntax. e.g. you're doing
[0,1,2][3,4,5]
which is two separate arrays jammed up against each other. It would have to be more like
[[0,1,2],[3,4,5]]
to be valid JSON. You encode to json LAST, after you've completely build your PHP data structure, not piecemeal in the middle of the construction process.
e.g.
foreach(...) {
$array[] = more data ...
}
echo json_encode($array);
My question is similar to this one: Highcharts how to use JavaScript variable as series data source? - except mine is a php variable.
I'm using https://github.com/2amigos/yii2-highcharts-widget this package with Yii2 and I've generated a data array which looks like this:
Array
(
[0] => {y: 37.50, color: "#BF0B23"}
[1] => 49.25
[2] => 52
)
I cast the numbers to floats when generating this array, but I couldn't do this with the object. When the graph is rendered the columns all work fine except for the one that I am trying to change the colour for.
The JS ends up like this "data":[37.5,49.25,"{y: 52.00, color: \"#BF0B23\"}"]. The js object being quoted basically means it isn't rendered. I've tried array_values(), (casting) and some other weird and wonderful manipulation to try and remove the quotes. I'm hoping there is a way to easily remove the quotes?
I guess you are trying to convert PHP hash into JSON, which then should be rendered by highcharts?
Try json_encode php function for that - http://php.net/manual/en/function.json-encode.php
Ok, I managed to figure out how to do it. Thanks #paweł-fus because your comment got me thinking about it a different way.
In my previous non-yii2, non 2amgios package I was generating my object as a string and writing it directly into JS.
if($d['ATTENDING'] === $data['ATTENDING'])
{
$a[] = array($data['ATTENDING'] => '{y: ' . number_format($data['PERCENTAGE'], 2) . ', color: "#BF0B23"}');
} else {
$a[] = array($data['ATTENDING'] => number_format($data['PERCENTAGE'], 2));
}
So my array either showed the column value, or if the column value was special it showed the value and i also changed its colour. This was represented as a JS object.
What I need to do was this though, create an inner array for the js object in php and typecast the value so it wasn't a string.:
$a[] = array($data['ATTENDING'] => ['y' => (float) number_format($data['PERCENTAGE'], 2), 'color' => '#BF0B23']);
I'm passing an associative array (id => val) using Ajax and receiving it with jQuery's $.getJSON which read the data properly and prepared the object. There is, however, very annoying sorting issue.
It appears that on Chrome and IE the data becomes sorted by the id part of the associate array. So if the array should be (5=> 'xxx', 3 => 'fff') it actually becomes (3 => 'fff',5=> 'xxx'). On FireFox it works as expected, i.e. not sorted.
Any ideas?
You can add a leading 0 for all integer indexes.
var json = { '05' => 'xxx', '03' => 'fff' };
Seems the best way is to avoid associative arrays at all. When you want to send an associate array simply send it as two separate arrays - one of keys and one of values. Here's the PHP code to do that:
$arWrapper = array();
$arWrapper['k'] = array_keys($arChoices);
$arWrapper['v'] = array_values($arChoices);
$json = json_encode($arWrapper);
and the simple JavaScript code to do whatever you'd like with it
for (i=0; i < data['k'].length; i++) {
console.log('key:' + data['k'][i] + ' val:' + data['v'][i]);
}
Another option is to return the data as an array of objects. That will ensure that the objects stay in the order that you return them.
Edit:
Basically, for each key > value pair, push it to a new array and json_encode that array.