简体   繁体   中英

How to prepare / build Multidimensional Array from Javascript to send to PHP

I must receive in PHP from Ajax/Javascript an array like below:

$search = $_POST['query'];
$search = array(
    'category1' => array('include' => array(93, 52),'exclude' => array(72)),
    'category2' => array('include' => array(93, 52)),
    'category3' => array('exclude' => array(72)),
    'category4' => array()
);

In my javascript page, the array is built by user actions before send it. The user select categories and items to build it.

For example, my final javascript array must look like below :

my_array = '{
        "category1":{
            "include":["93","52"],
            "exclude":["72"]
        },
        "category2":{
            "include":["93","52"]
        },
        "category3":{
            "exclude":["72"]
        },
        "category4":[]
        }';

i try many query.push but it doesn't work when many categories are selected.

I am unable to:

  • Add item in new category when a category already exists in my global array
  • Remove a specific item from specified category because the identifier is a variable:

(example: remove '52' in "category2":{"include":["93","52"]},

Description:

  • A category item id can be placed in 'include' section OR 'exclude' section of specified category (but not in both)

  • An item (tag) under category can have 3 status (classes):

    • btn-default: item no selected, item id must be remove of specified array
    • btn-danger: item excluded, item id must be present in 'exclude' list of specified array
    • btn-primary: intem included, item id must be present in 'include' list of specified array

Here is the jsfiddle link: JSFIDDLE

thanks.

In Javascript, this is an array: [] and this is an object: {} . So this is how I would create my array in JS:

var my_array = [
  {'category1':{'include':[1,2,3], 'exclude':[5]}},
  {'category2':{'include':[3,4,5], 'exclude':[6,7,8]}},
  {'category3':{'include':[1,2], 'exclude':[7]}}
  ];

Here is a fiddle demonstrating how to push a new value into the array: https://jsfiddle.net/h15emr8j/

If you want to push a value into a specific part of the array, here's how you do it:

my_array[0].category1.exclude.push(100);

you can follow below logic to achieve what you want :

var my_array={}; // creating empty array object

my_array.category1={}; // creating new filed in my_array

var include1 = new Array(); //creating include array for category 1
include1.push("93"); // push include values
include1.push("52");

var exclude1 = new Array(); // creating exclude array for category1, if you want
exclude1.push("72"); // push exclude values


my_array.category1.include=include1; // finally add it to category1
my_array.category1.exclude=exclude1;

alert(JSON.stringify(my_array)); // convert your object to JSON string

Now if you want to add new value to include and exclude of category1 then you simply need to push those values in their respective arrays.

The simplest solution could be something like this.

const jsonArray = [{
  category: {
    include: ["93", "52"],
    exclude: ["72"]
  }
  ..
}];

JS code

my_array = {"category1": {"include": ["93", "52"], "exclude": ["72"]}, "category2": {"include": ["93", "52"]}, "category3": {"exclude": ["72"]}, "category4":[]};
console.log(my_array);
$.post("array.php", {query: my_array}, function( data ) {
    console.log(data);
}, "text");

PHP code

<?php
    $search = $_POST['query'];
    print_r($search["category1"]["exclude"]);

So a few good things to learn here. Initializing arrays in javasript:

var arr = ['include','exclude']; 
arr['include'] = []; 
arr['exclude'] = []; 

Next we need use ajax to send our array to the php script:

var jsonString = JSON.stringify(arr);

$.ajax({
url: 'myscript.php',
type: 'POST',
data:{
      arr: jsonString
     },
success: function(result){
//continue with results
},
error: function(result){
//continue with results
}
});

Finally on the php side:

$arr = json_decode($_POST['arr']);

//code to execute

echo json_encode($arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM