How to iterate PHP array received as JSON?

Asked

Viewed 188 times

0

I got the following JSON, that I create by the method JSON.stringify(dados), and walkthrough ajax to the php:

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

When I receive it in PHP, I do the conversion by 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 the /. For example: dado[departamento] = "5aac50..."

Follow the codes that aren’t 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();
        }
  • This is not clear, much code but it does not go straight to the point. Quall the doubt actually?

  • Excuse the lack of clarity. In fact it is difficult to explain everything. My intention is to create a JS library that allows you to follow patterns for creating forms, without having to keep developing a function for each form. I am scanning the patterns and when I find a select field that has been populated with Collection results, I am adding _$oid/ before its _id to be able to turn into Objectid and refer it to coutra Collection. I don’t know if it was clear, but the code worked as the changes I commented in the answer below. Vlw for help!

1 answer

0


first. The format of the data you put into question is not a Array, and yes a Objeto. An array JSON possesses [] delimiting its content. An object has {}.

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

Follow an example code that changes the value of the'department 'field to keep 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");
}
  • In fact, I am created a function library in Js to facilitate the creation of forms. Thus, I do not intend to directly reference the field: $json->department. But your answer was valid because I was referencing wrong: $given[$key] = $tags[1]; Now I’m referencing as you showed: foreach ($given as $key => $value) { $search = '_$oid/'; if (strripos($value, $search) === false) { // Does nothing } Else { $given->$key = explode('/', $given->$key)[1]; } }

  • Okay then, nice to be able to help with something.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.