How to iterate PHP array received as JSON? [duplicate]

0

I have the following JSON , which I create by JSON.stringify(dados method), and I pass via ajax to php :

{"nome":"nome_da_pessoa", "registro":"registro_da_pessoa", "departamento":"_$oid/5aac50..."}

When I get into PHP, I'm converting to json_decode($_POST['dado']); .

I would like to iterate this array, and when I find the value _ $ oid /, separate and update the item only with the part after /. For example: dado[departamento] = "5aac50..."

Follow the codes that are not working.

Js code:

var dados = {};
    $("form input").each(function () {
        var campo = $(this).attr("name"), valor = $(this).val();
        dados[campo] = valor;
    });
    $("form select").each(function () {
        if ($(this).attr("carrega") == "s") {
            var campo = $(this).attr("name"), valor = "_$oid/" + $(this).val();
            dados[campo] = valor;
        } else {
            var campo = $(this).attr("name"), valor = $(this).val();
            dados[campo] = valor;
        }
    });
    dados["excluido"] = "n";
    dados["logado"] = "n";
    var dado = JSON.stringify(dados);

    $.ajax({
        url: 'funcoes/registros.php',
        data: {
            "funcao": "incluidado",
            "collection": collection,
            "dado": dado
        },
        type: 'post',
        dataType: 'json',
        cache: false,
        beforeSend: function (xhr) {
        },
        error: function (jqXHR, textStatus, errorThrown) {
        },
        success: function (dados) {
            preenchetabela(collection);
        }
    });

PHP code:

$collection = $_POST['collection'];
        $dado = json_decode($_POST['dado']);

        // CONSEGUIR ALTERAR O $oid_
        foreach ($dado as $key => $value) {
            $procura = '_$oid/';
            if (strripos($value, $procura) === false) {
                // não altera nada
            } else {
                // remove o _$oid do valor
                $tags = explode($procura, $value);
                $dado[$key] = $tags[1];
            }
        }

        try {
            $insert = new MongoDB\Driver\BulkWrite; // Monta o BulkWrite
            $insert->insert($dado);
            $conexao->executeBulkWrite($bd . "usuarios", $insert);
            echo json_encode("Registro realizado com sucesso!");
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    
asked by anonymous 26.03.2018 / 03:54

1 answer

0

first. The data format you put in the question is not a Array , but a Objeto . An array JSON has [] delimiting its content. An object has {} .

I do not know the structure of objeto json that you are passing to your PHP code, however I believe that the way you are looking for the value to replace is unintuitive because it is a structure with 'keys' and 'values'. You could simply search for the desired key, or, knowing the structure, could simply change the value of the key directly, knowing that it must exist beforehand.

Following is a code example that changes the value of the 'department' field to hold the value after the '/' delimiter.

$json = json_decode('{"nome":"nome_da_pessoa", "registro":"registro_da_pessoa", "departamento":"_$oid/5aac50..."}');

// Percorrendo os campos do objeto (desnecessário..)
// foreach($json as $k => $v) {
//   if($k === 'departamento') {
//     echo("achou..");
//     $json->{$k} = explode("/", $v)[1];
//     break;
//   }
// }

// Acessando diretamente o campo (poderia verificar a existencia antes..)
$json->departamento = explode('/', $json->departamento)[1];

foreach($json as $k=>$v) {
  echo($k . " = " . $v . "\n");
}
    
26.03.2018 / 14:21