If with parameters, you mean "keys" then you can do using array_keys
that will take the key name, code, etc from the variable $parametrosdBase
and use the array_key_exists
to check if the key exists (since you said the values can be empty, false I suppose they can be null
also).
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 switched the isset
for array_key_exists
, because if you have any value with null
, then he will give false
chance 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 to which they refer are usually called "keys" or Keys (see), 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
Just want to check if the received string is a JSON?
– mauricio caserta
@mauriciocaserta Hi, no, it’s to check if the parameters were followed.
– Elaine
These parameters are on the root level of json?
– Guilherme Nascimento
You want to compare the keys to
$parametrosdBase
with json keys or you also want to compare $parametrosdBase values with values within json?– Guilherme Nascimento
@Guilhermenascimento Hi, maybe I used the wrong words, not to compare values. it goes like this: I have that base array, and I want to check in a JSON format string that all parameters of the base array are also present in the encoded string, regardless of whether they are empty, false, 0 etc..
– Elaine
I think she wants to check if there are 'name', 'code' keys inside the array?
– mauricio caserta
Elaine I did not state that it was comparing values, I asked if they were values and keys or just keys, I will assume that are the keys you need, I will formulate an answer.
– Guilherme Nascimento