JQuery, Ajax, Json, PHP multidimensional associative array - php

I am trying to loop through a multidimensional associative array retrieved via jquery/ajax from a php file.
The php array looks like this:
$pink = array ( "newarray" => array
( "varietyOne" => array
("name" => "Poublout", "year" => 2002),
"varietyTwo" => array
("name" => "Gerarde", "year" => 2003),
"varietyThree" => array
("name" => "Encore", "year" => 1956),
"varietyFour" => array
("name" => "Toujours", "year" => 1957),
"varietyFive" => array
("name" => "J'aime", "year" => 1958),
"varietySix" => array
("name" => "Alisee", "year" => 2001)
),
"varNumber" => array
("varietyOne",
"varietyTwo",
"varietyThree",
"varietyFour",
"varietyFive",
"varietySix"
)
);
print json_encode($pink);
The js looks like this:
$(document).ready(function () {
$('.clicker').click(function () {
$.ajax({
type: 'GET',
url: 'another.php',
dataType: 'json',
success: function (brandon) {
for (var i = 0; i < brandon.newarray.length; i++) {
var catName = brandon.varNumber[i];
for (var wineName in brandon.newarray[i][catName]) {
console.log(branond.newarray[i][catName][wineName]);
}
}
}
});
});
});
And here is the json rather than the php:
{"newarray":
{"varietyOne":{"name":"Poublout","year":2002},
"varietyTwo":{"name":"Gerarde","year":2003},
"varietyThree":{"name":"Encore","year":1956},
"varietyFour":{"name":"Toujours","year":1957},
"varietyFive":{"name":"J'aime","year":1958},
"varietySix":{"name":"Alisee","year":2001}},
"varNumber":
["varietyOne","varietyTwo","varietyThree","varietyFour","varietyFive","varietySix"]}
I've tried several different loops, changing my array values, but I can't make anything work. I can call an individual key=value pair in the array, but I can't get it to loop through all values.
Thank you.
And the results of console.log(brandon)
Object { newarray={...}, varNumber=[6]}
newarray
Object { varietyOne={...}, varietyTwo={...}, varietyThree={...}, more...}
varietyFive
Object { name="J'aime", year=1958}
varietyFour
Object { name="Toujours", year=1957}
varietyOne
Object { name="Poublout", year=2002}
varietySix
Object { name="Alisee", year=2001}
varietyThree
Object { name="Encore", year=1956}
varietyTwo
Object { name="Gerarde", year=2003}
varNumber
["varietyOne", "varietyTwo", "varietyThree", 3 more...]
0 "varietyOne"
1 "varietyTwo"
2 "varietyThree"
3 "varietyFour"
4 "varietyFive"
5 "varietySix"
So, the loop now outputs to console, but I want the text to be displayed on my site. Normally I use a $('#somediv').append(brandon.(whateverelse); and the information will appear. In this case it does not.

You shouldn't need the varNumber array.
All you need is:
for (var index in brandon.newarray) {
console.log(index);
console.log(brandon.newarray[index]);
console.log(brandon.newarray[index]['name']); // or brandon.newarray[index].name
console.log(brandon.newarray[index]['year']); // or brandon.newarray[index].year
}
In this case, index will be varietyOne, varietyTwo, etc.

Related

PHP handling multi-dimensional object//array from AJAX Jquery post

I have a large multi-dimensional object of arrays in JS that I am trying to pass to PHP using Ajax. The keys of some of the array values are written arrays test[key], and in PHP I want them to be read as such test => array([key] => 123). Note, I am working in Wordpress.
Working example
JS:
var args = {
'action' : 'save',
'test[key1]' : ['123', 'abc']
}
var request = $.ajax({
url: settings.get('ajaxurl'),
data: args,
type: 'post',
success: function(response) { // }
});
PHP print_r on output:
[action] => save
[test] => Array
(
[key1] => Array
(
[0] => 123
[1] => 234
)
)
However, I want to send all of the test[key1] (and a lot more data) at the second level of the object. I have a lot of data and need them grouped accordingly.
Not working example
JS:
// simple changing the args
var args = {
'action' : 'save',
'data' : {
'test[key1]' : ['123', 'abc']
}
}
PHP print_r on output:
[action] => save
[data] => Array
(
[test[key1] => Array
(
[0] => 123
[1] => 234
)
)
This seems to be really difficult to explain - but it looks like PHP isn't parsing the array keys properly when it's not on the top level of the array. Am I doing something wrong // is there a way around this? I can provide more insight if needed, I attempted to make this as clear as possible.
When printing the keys of the data array, it prints them without the final ]. So it shows test[key1 instead of what I am expecting. Maybe they get stripped somewhere?
I think you need to stringify the data
var request = $.ajax({
url: settings.get('ajaxurl'),
data: JSON.stringify(args),
type: 'post',
success: function(response) { // }});
Then use json_decode to make it useful in PHP.
Edit:
This might get you where you want to go...
var args = {
'action' : 'save',
test : {
key1 : [
'123',
'abc' ]
} }
Since JavaScript does not allow for associative arrays.
Please try this args, this will give multi-dimensional array result.
var args = {
'action' : 'save',
'data' : {
'test': {
'key1' : ['123', 'abc']
}
}
}

JS post Object via JSON

I am aware, that there are many questions regarding this topic in general... however, so far I haven't found a solution to my specific problem:
I have objects, looking something like that:
var myArray = [];
var ArrayObject = {
power: 10,
name: 'arrayobject'
}
myArray.push(ArrayObject);
var myObject = {};
myObject.Name = "test";
myObject.myArray = myArray.slice(0);
Now I would like to post this data to php:
post("./output.php", myObject,'post');
Well, this does not work... I also tried it with
var myJSON = JSON.stringify(myObject);
and on PHP Side with
//$myObj = json_decode($_GET['myObject']);
but that does not work as well... if I remove the 'myArray' from 'myObject' that works, but having all data in one object would be very nice.
Can anyone tell me how to do that or point me in the right direction?
Thank you very much!
If you make request like this
function test(){
var myArray = [];
var ArrayObject = {
power: 10,
name: 'arrayobject'
}
myArray.push(ArrayObject);
var myObject = {};
myObject.Name = "test";
myObject.myArray = myArray.slice(0);
jQuery.post('output.php', {
data: {
myObject:myObject
},
}, function(data) {
console.log(data);
});
}
then you access the data in PHP like
$_POST['data']['myObject']
Whole $_POST will look alike
array (
'data' =>
array (
'myObject' =>
array (
'Name' => 'test',
'myArray' =>
array (
0 =>
array (
'power' => '10',
'name' => 'arrayobject',
),
),
),
),
)
You don't need to json_decode it automatically does

Need a map reduce function in mongo using php

Need a map reduce function by mongo in php
This my mongo structure
[_id] => MongoId Object (
[$id] => 4fcf2f2313cfcd2454500000d
)
[id] => 454
[table] => people
[news] => Array (
[03-06-2012] => 2
[04-06-2012] => 3
[05-06-2012] => 5
[06-06-2012] => 4
)
Here I try to sum the array news with below code,
$map = new MongoCode('function() { emit(this.news, 1); }');
$reduce = new MongoCode('function(previous, current) {
var count = 0;
for (index in current) {
count = count + current[index];
}
return count;
}');
$sales = $db->command(array(
'mapreduce' => 'mycollection',
'map' => $map,
'reduce' => $reduce,
'query' => array('table' => 'people'),
'out' => 'news'
));
//pr($sales);exit;
$users = $db->selectCollection($sales['result'])->find();
foreach ($users as $user) {
//echo "{$user['_id']} had {$user['value']} sale(s).\n";
pr($user);
}
When pr($user)
Array
(
[_id] => Array
(
[04-06-2012] => 0
[08-06-2012] => 2
[11-06-2012] => 6
)
[value] => 39540
)
Where I expected a value will be 8 instead of 39540.
How I can correct this function and how to the add a field sum as array sum of 'news' to original collection(mycollection) ?
I am not familar with map reduce functions in mongo.
When calling emit(), the first parameter is the key you'll be reducing on (or grouping, for this example). The second parameter is the value being emitted for that key, which can be anything. For your example, you probably mean to emit the sum of all values in the news field, using the document's ID as your key:
var map = function() {
var total = 0;
for (count in this.news) {
total += count;
}
emit(this._id, total);
}
In this case, a placeholder reduce function can be used (since each emitted key will be unique, there's very little reduction to be done):
var reduce = function(key, values) {
var total = 0;
values.forEach(function(v) { total += v; });
return total;
}
However, as I mentioned in the Google Group post, you may be better off doing this with pure PHP:
$cursor = $collection->find(array(), array('news' => 1));
$cursor->snapshot();
foreach ($cursor as $document) {
$collection->update(
array('_id' => $document['_id']),
array('$set' => array('sum' => array_sum($document['news']))),
array('multiple' => false)
);
}
With map/reduce, you'd still have to examine its results and update your records. This would avoid the need to execute JavaScript through Mongo, and should be more performant. And if you can utilize $inc to update the sums as the news field is modified on a per-document basis, that will be even better. The above snippet would still be useful for initializing sum fields across the collection, or correcting any drift if things get out of sync with per-document increments.
Note: see snapshot() in the documentation for the reasoning behind that method call in the example above.
While jmikola's answer gives me wright track to deal with mongo map reduce functions.
I am adding this answer in order to help future visitors.
The following map-reduce function works perfectly to my requirement.
This will sum all values in the news field to new collection called news created in command by adding ("out" => "news").
Map-Reduce Function
$map = new MongoCode('function() {
var total = 0;
for (count in this.news) {
total += this.news[count];
}
emit(this._id, {id: this.id, total: total});
}');
$reduce = new MongoCode('function(key, values) {
var result = {id: null, total: 0};
values.forEach(function(v) {
result.id = v.id;
result.total = v.total;
});
return result;
}');
$sales = $db->command(array(
'mapreduce' => 'mycollection', // collection name
'map' => $map,
'reduce' => $reduce,
'query' => array('table' => 'people'),
"out" => "news" // new collection name
));
The result will be news collection with sum as total and id of actual document
Output
[_id] => MongoId Object (
[$id] => 4fd8993a13cfcd4e42000000
)
[value] => Array (
[id] => 454
[total] => 14
)

Jquery serialize to PHP array

I want to send the result of a HTML sorting to the server by serializing with jQuery.
This works if I only send the result:
var result = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: '/cms/update/',
data: result,
});
But I try to send a Javascript Object to the server wich contains the serialized 'result'
In PHP I get an array with result_2 as the serialize object:
Array
(
[ids_1] => miti_1_ti_2_col_2
[article_id] => article_id_2
[result_1] =>
[ids_2] => miti_1_ti_2_col_1
[result_2] => article_id[]=2
)
How can I get this result to be an array in PHP?
As I understood "result" is a serialized object too.
So you have to unserialize result at first.
Then you have to unserialize result2. Something like that:
$res1 = unserialize($data);
if (isset($res1['result_2']){
$res2 = unserialize($res['result_2']);
}
Updated:
I don't know if your result_2 in data is already serialized. Therefore here are two examples:
if result_2 is not serialized in data:
$arr = array('id_1' => 'miti_1_ti_2_col_2',
'article_id' => 'article_id_2',
'result_1' => '',
'ids_2' => 'miti_1_ti_2_col_1'
);
$arr['result_2'] = $arr;
$test1 = serialize($arr);
$test1 = unserialize($test1);
If result_2 is already serialized in data:
$arr = array('id_1' => 'miti_1_ti_2_col_2',
'article_id' => 'article_id_2',
'result_1' => '',
'ids_2' => 'miti_1_ti_2_col_1'
);
$arr['result_2'] = serialize($arr);
$test2 = serialize($arr);
$test2 = unserialize($test2);
$test2['result_2'] = unserialize($test2['result_2']);
This code works I checked out it. If your code still doesn't work check result in JS.
If I've understood correctly, you need to convert a string such as action[]=1&action[]=2 into an array?
If that is right you can use the following: (when $_POST["order"] = "action[]=1&action[]=2")
$result = preg_split("/&?action\[\]=/", $_POST["order"], -1, PREG_SPLIT_NO_EMPTY);
This will give you:
Array
(
[0] => 1
[1] => 2
)

How can I post a JSON multi-dimensional data via Jquery.post?

How can I post a JSON multi-dimensional data via $.post? For instance, I have this multi-dimensional array in JSON format:
{
"file":
{
"name" : "1024x768.jpg",
"type" : "image\/jpeg",
"tmp_name" : "C:\\wamp\\tmp\\php8F59.tmp",
"error":0,"size":469159
}
}
I will use Jquery.post() to post the JSON data.
$.post("process.php",'{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}}',function(xml){
});
So I can get this array in process.php using print_r($_POST):
Array
(
[file] => Array
(
[name] => 1024x768.jpg
[type] => image/jpeg
[tmp_name] => C:\wamp\tmp\phpA1.tmp
[error] => 0
[size] => 469159
)
)
Is this possible?
Try this:
$.post("process.php",{"file":{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}},function(xml){
});
that should give you the desired array on the php side
Edit: this works since jQuery 1.4 and above
$jsonArray ='{"file":{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}}';
$arr = JSON.stringify($jsonArray);
$.post("/url",{data:$arr},function(){
});
in the php file do
$json = json_decode($_POST['data']);
print_r($json);
Edit
may be this will help, i have not tested it though...
var file=[];
file["name"]="1024x768.jpg";
file["type"]="image/jpeg";
file["tmp_name"]="C:\wamp\tmp\phpA1.tmp";
file["error"]="0";
file["size"]="469159";
var myObject = new Object();
var enumm=["name","type","tmp_name","error","size"];
function getEnum(index){
return enumm[index];
}
$.each(file,function(i,j){
myObject[getEnum(i)]=file[getEnum(i)];
});
$.post("/url",{data:$.param(myObject)},function(xml){
});
on the php side do
$json = parse_str($_POST['data'], $data);
print_r($json);

Categories