JSON manipulation with PHP

Asked

Viewed 108 times

2

I have that code PHP that is manipulating the JSON created in the beginning, in the end it will print/list one foreach with all the data.

My question is the following, I don’t want to print all 3 lines, I want to print only the second line of my JSON for example.

How could I do that?

<?php

$json_str = '{"empregados": '. 
        '[{"nome":"Jason Jones", "idade":38, "sexo": "M"},'.
        '{"nome":"Ada Pascalina", "idade":35, "sexo": "F"},'.
        '{"nome":"Delphino da Silva", "idade":26, "sexo": "M"}'.
        ']}';

$jsonObj = json_decode($json_str);
$empregados = $jsonObj->empregados;

foreach ( $empregados as $e )
{
    echo "nome: $e->nome - idade: $e->idade - sexo: $e->sexo<br>"; 
}
?> 
  • print only line 2 ($empregados[1]) because the array in PHP has its start by 0 that being the position 1 and so on.

  • $empregados is an array, so to access the second line just do $empregados[1].

1 answer

1


In your case $empregados will be a array, then just access the second position of it, has no mysteries.

$empregados = $jsonObj->empregados;
$segundoEmpregado = $empregados[1];

echo $segundoEmpregado->nome;

Simple as that. As you know the position, just access it directly, as this will be an O(1) operation, given that the array in PHP, even with numerical indexes, it is implemented in the form of a map, relating key/value. Thus, there will be no costs in the application to search within the array the desired value.

It was suggested in another reply to make a loop with a check:

foreach($empregados as $key => $empregado){
    if($key == 1){
        //ação somente para o índice 1 (que é o segundo elemento do array)
    }
}

This produces the expected result, but is unnecessary for this problem. This solution will always run through the array whole, which does not justify if you only need a position. The search will be O(n) and if the array is very large it will bring losses in the performance of your application.

This solution may be useful when you need multiple values, which make the O(n) search viable. Search for example a large list of positions that is generated dynamically:

foreach($empregados as $key => $empregado){
    if(in_array($key, $posicoes)){
        // ...
    }
}

In all cases, it is always good to warn about using the loose comparison, as it can generate side effects difficult to identify in maintenance.

Browser other questions tagged

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