问题
I have an array in angularjs, Example as below.
$scope.order.qty='20';
$scope.order.adress='Bekasi';
$scope.order.city='Bekasi';
This array can post with this code
$http({
          method  : 'POST',
          url     : '<?php echo base_url(); ?>add_order',
         data    : $scope.order,
          headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
         })
I can get all variable with
$_POST = json_decode(file_get_contents('php://input'), true);
$_POST['qty'];
$_POST['address'];
$_POST['city'];
But I'm confused if array multi-dimensional like this :
$scope.items[1].kode_produk='PR_1';
$scope.items[2].kode_produk='PR_2';
$scope.items[3].kode_produk='PR_3';
How to post and get variable from array multi-dimensional like this ?
回答1:
Is one way
in JavaScript send data $scope.items, for example:
$http({
          method  : 'POST',
          url     : '<?php echo base_url(); ?>add_order',
         data    : $scope.items,
          headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
         })
and on the site PHP code write:
$_POST = json_decode(file_get_contents('php://input'), true);
var_dump($_POST); die();
and analyze the data structure.
回答2:
You can pass array like it:
$http({
      method  : 'POST',
      data    : { items: $scope.items }
      ...
     })
getting data:
$_POST = json_decode(file_get_contents('php://input'), true);
$items = $_POST['items'];
回答3:
Your json will look like this if you send $scope.items :
[
  {
    "kode_produk": "PR_1"
  },
  {
    "kode_produk": "PR_2"
  },
  {
    "kode_produk": "PR_3"
  }
]
Which results to this php array after $input = json_decode(...):
array (size=3)
  0 => 
    object(stdClass)[1]
      public 'kode_produk' => string 'PR_1' (length=4)
  1 => 
    object(stdClass)[2]
      public 'kode_produk' => string 'PR_2' (length=4)
  2 => 
    object(stdClass)[3]
      public 'kode_produk' => string 'PR_3' (length=4)
You have an array of objects, not a multidimensional-array!
You can iterate over the items like:
foreach($input as $item)
{
    echo $item->kode_produk;
}
来源:https://stackoverflow.com/questions/39162136/how-to-post-array-multidimensional-angular-js