简体   繁体   English

如何从Javascript准备/构建多维数组以发送到PHP

[英]How to prepare / build Multidimensional Array from Javascript to send to PHP

I must receive in PHP from Ajax/Javascript an array like below: 我必须在PHP中从Ajax / Javascript接收如下数组:

$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. 在我的JavaScript页面中,该数组是在发送之前由用户操作构建的。 The user select categories and items to build it. 用户选择类别和项目来构建它。

For example, my final javascript array must look like below : 例如,我的最终javascript数组必须如下所示:

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. 我尝试了许多query.push,但是当选择了许多类别时它不起作用。

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"]}, (例如:在“ category2”:{“ include”:[“ 93”,“ 52”]}中删除'52',

Description: 描述:

  • A category item id can be placed in 'include' section OR 'exclude' section of specified category (but not in both) 可以将类别项目ID放在指定类别的“包括”部分或“排除”部分中(但不能同时放在两者中)

  • An item (tag) under category can have 3 status (classes): 类别下的项目(标签)可以具有3个状态(类):

    • btn-default: item no selected, item id must be remove of specified array btn-default:未选择项目,必须删除指定数组的项目ID
    • btn-danger: item excluded, item id must be present in 'exclude' list of specified array btn-danger:项目被排除,项目ID必须出现在指定数组的“排除”列表中
    • btn-primary: intem included, item id must be present in 'include' list of specified array btn-primary:包含intem,项目ID必须存在于指定数组的“ include”列表中

Here is the jsfiddle link: JSFIDDLE 这是jsfiddle链接: JSFIDDLE

thanks. 谢谢。

In Javascript, this is an array: [] and this is an object: {} . 在Javascript中,这是一个数组: [] ,这是一个对象: {} So this is how I would create my array in JS: 所以这就是我要在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/ 这是演示如何将新值推入数组的小提琴: 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. 现在,如果要添加新值以包括排除 category1 ,则只需要将这些值推入它们各自的数组中即可。

The simplest solution could be something like this. 最简单的解决方案可能是这样的。

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

JS code JS代码

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代码

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

So a few good things to learn here. 因此,这里有一些好东西要学习。 Initializing arrays in javasript: 在javasript中初始化数组:

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

Next we need use ajax to send our array to the php script: 接下来,我们需要使用ajax将数组发送到php脚本:

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: 最后在php端:

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

//code to execute

echo json_encode($arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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