2

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 ?

Suraj Sakhare
  • 363
  • 1
  • 4
  • 12
Edu Arif
  • 123
  • 1
  • 1
  • 7

3 Answers3

1

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'];
Yrysbek Tilekbekov
  • 2,685
  • 11
  • 17
1

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;
}
SpazzMarticus
  • 1,218
  • 1
  • 20
  • 40
0

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.

Marcin Dargacz
  • 146
  • 1
  • 5