JSON Array in NgCordova and PHP

Always I sent json object to the server (php) to save in the database but always sent only one object.
Now no need to send a json array and therein lies the problem.
I can not make foreach work to save the attributes in the database (MySQL).
In JavaScript is done as follows:

$scope.arrayExample.push (objectExampleJSON); // {Id: 1, name: 'test'}

In PHP basically like this:

if (isset ($_REQUEST ['package']))
   package = $($_REQUEST ['package']);

$ arr = json_decode ($package, true);

foreach ($arr as $obj) {
   $sql = "INSERT INTO ................)
VALUES (".$Obj['example']") .......

It does not work that way. Down a code obtained by other forum with these test data (below) works normally.

<? php
$ arr = json_decode ('[{"var1", "9", "var2": "16", "var3": "16"}, {"var1", "8", "var2": "15" "var3": "15"}] ', true);

foreach ($arr as $item) {// foreach element in $ arr
     $uses = $item ['var2']; //etc
     echo $item ['var2'];
}
?>

Where am I going wrong?

first you should est $arr correctly:

$arr = json_decode ('[{"var1", "9", "var2": "16", "var3": "16"}, {"var1", "8", "var2": "15" "var3": "15"}] ', true);

$arr not $ arr.

And each item in your array is an object --> so i would use reference syntax: $item->var2

Disregard this error $ err (with space) is a problem when pasting the code here. Yet still not working …

Still not working because this json isn’t valid…

This is just one example (wrong by the way), but in my json the code is correct → {id: 1, name: ‘test’}
I add this object to a variable → arrayExample.push (objectJsonExample);
This object (with added push), send to php.

Have you inverted $ in the second line:

if (isset ($_REQUEST['package'])) {
     $package= $_REQUEST['package'];
}

Sorry for these basic errors, I write here at night forum and was tired. In my original code is correct. The foreach does not work properly.
This should not work? :

foreach ($arr as $item) {  
 echo $item['example'];
}

…please post full code, javascript and php, so we can help better…

[HTML]

<div class="list" ng-repeat="produto in produtos track by produto.nome">
          <div class="item item-divider">
            <h2>{{produto.nome}}</h2>
            <p>R$ {{produto.valor}}</p>
          </div>
          <label class="item item-input item-select">
            <div class="input-label">
            Qtd
            </div>
            <select ng-model="produto.qtd">
              <option value=""></option>
              <option ng-selected="true" value="0">0</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
            </select>
          </label>
          <button ng-show="!verificaCarrinho(produto)" class="button button-block button-balanced icon-right ion-ios-cart" ng-click="add(produto);" ng-disabled="myForm.$invalid">
            Adicionar ao Carrinho          
         </button>     
        </div>

[JS Add]

$scope.add = function(produto) {
    for (var i = 0; i < $scope.carrinhoCompras.length; i++)
      if ($scope.carrinhoCompras[i].id_produto === produto.id_produto)
        return;
    if (produto.qtd <= 0 || produto.qtd === undefined) {
      var alert = $ionicPopup.alert({
        title: 'Atenção',
        content: Mensagens.getInformeQtdMaiorZero()
      })
      return;
    }
    else
      $scope.carrinhoCompras.push(produto);
    console.log($scope.carrinhoCompras);
  };

[JS Send]

$http.get(
            Servidor.getUrlServidor() + Servidor.getUrlCadastrarPedido(), {
              params: {
                "pedido": $scope.carrinhoCompras
              },
              timeout: Servidor.getTimeOut()
            }).then(function(resp) {
            if (resp.data.validar == true) {    
              $ionicLoading.hide();
              $ionicScrollDelegate.scrollTop();
              $scope.pedidosCadastrarModal.hide();
            } else {
              var alert = $ionicPopup.alert({
                title: 'Atenção',
                content: Mensagens.getErroServidor()
              })

              $ionicLoading.hide();
            }
          }, function(err) {
            console.error('ERR', err);
            var alert = $ionicPopup.alert({
              title: 'Atenção',
              content: Mensagens.getErroServidor()
            })
            $ionicLoading.hide();
          }) // Http

[PHP]

<?php
    header('Access-Control-Allow-Origin: *');
    require('conn.php');

    // Atribuição de valores
    if (isset($_REQUEST['pedido'])) {
        $pedido = ($_REQUEST['pedido']);        
  }
  else {
        $pedido = '';        
  }

    $arr = json_decode($pedido, true);    

  // Criar conexão
  $conn = new mysqli($servername, $username, $password, $dbname);
  // Checar conexão
  if ($conn->connect_error)
    die("Erro conexão: " . $conn->connect_error);
  else
  {        
          // YYYY-MM-DD
          $dataPedido = date('Y-m-d H:i:s');          
                            
        foreach ($arr as $obj) {  
        $sql = "INSERT INTO PEDIDOS (FK_ID_PRODUTO, PRECO)
        VALUES ('".$obj['id_produto']."','"
                          .$obj['valor']."')";

        // Registro inserido com sucesso
        if ($conn->query($sql) === TRUE)
            $validar = true;
        else
            $validar = false;       
        }     

        // Empacotamento Json
        echo json_encode(array('validar' => $validar));

        $conn->close();
    }
?>

Quickly explaining the operation: When you click the button, I add the object to $ scope.carrinhoCompras, which will later be sent to the php and driven at foreach.
Sorry indentation, when pasting the code here is mangled.

att

I’ve done a very fast check to your code…

Seems that:

is an array (you use push), so when you send data to PHP, you need to convert it to json. To do this, change:

      params: {
        "pedido": $scope.carrinhoCompras
      },

to

      params: {
        "pedido": JSON.stringify($scope.carrinhoCompras)
      },

Let me know if this resolve…

Good evening,

Thank you friend, really solved the problem.

att