Check if default is followed, JSON and PHP

0

There is a small request pattern with several parameters, but I'll simplify it this way:

$parametrosdBase = array('nome' => false, 'codigo' => 83474, etc..

I get a string in JSON format that should theoretically CONTAIN these parameters, ie it has to have all those parameters that I showed in the array above.

Yes I could simply check if each parameter exists manually but as it is in large scale I would like a function that would do this automatically.

obs: the parameter can even be vazio, false, 0 how important is it exist .

    
asked by anonymous 25.09.2015 / 22:31

2 answers

2

If with parameters, you mean "keys" then you can do using array_keys that will get the keys name, code, etc of variable $parametrosdBase and use array_key_exists to check if the key exists (already that you said that the values can be empty, false I suppose they can be null too).

Example:

<?php
$parametrosdBase = array('nome' => false, 'codigo' => 83474);

$json = json_decode('{"nome": "João", "codigo": false, "foo": "hello" }', true);

$chaves = array_keys($parametrosdBase);

$error = null;

foreach ($chaves as $value) {
    if (false === array_key_exists($json[$value])) {
        $error = 'Parametro "' . $value . '" não encontrado';
        break;
    }
}

if ($error) {
    echo $error;
} else {
    echo 'Todos parametros da base encontrados!';
}

isset vs array_key_exists

I've changed isset to array_key_exists , because if it has any value with null , then it will give false use isset , even if the key exists.

<?php
$search_array = array('first' => null, 'second' => 4);

// Retorna false
isset($search_array['first']);

// Retorna true
array_key_exists('first', $search_array);

What are keys in an array

Note that these parameters are generally referred to as "keys" or keys, see:

PHP:

array('nome'                  => 'João');
        ^---Isto é uma chave       ^-----Isto é um valor de uma chave

Json:

{'nome':                     'João'};
    ^---Isto é uma chave       ^-----Isto é um valor de uma chave
    
25.09.2015 / 22:59
0

Try the following code:

$entrada = json_decode( $json, true );
$params = array( ... );
$intersecao = array_intersect_assoc( $entrada, $params );
$sucesso = count( $intersecao ) == count( $params );
    
26.09.2015 / 05:12