Retrieve php array data through index value

0

My array in print_r looks like this:

[
    {
        "id": "A220", 
        "name": "Dipirona", 
        "symbol": "R$", 
        "rank": "1", 
        "price_br": "8.4", 
        "price_usd": "2.0"
        "total_supply": "287.0", 
        "max_supply": "21000.0", 
        "last_updated": "1519152868"
    }, 
    {
        "id": "A220", 
        "name": "Eno", 
        "symbol": "R$", 
        "rank": "3", 
        "price_br": "2.4", 
        "price_usd": "1.0"
        "total_supply": "341.0", 
        "max_supply": "1200.0", 
        "last_updated": "1615122869"
    }
]

How to retrieve the values of ID: A220, for example, what are the product data "Dipirone", and store in another array only the data of "Dipirona"?

    
asked by anonymous 20.02.2018 / 20:13

2 answers

1

As far as I understand, you want to filter this array by the id index and name . To do this you can use the array_filter function of PHP.

Example:

Filtering this array by A220 and name Dipirona

<?php 

    $arr = "..."; //Array que você mandou no exemplo acima

    $novoArray = array_filter($arr, function($item) {
        return $item['id'] == "A220" && $item['name'] == "Dipirona"; 
    });

Result:

Array
(
    [0] => Array
        (
            [id] => A220
            [name] => Dipirona
            [symbol] => R$
            [rank] => 1
            [price_br] => 8.4
            [price_usd] => 2.0
            [total_supply] => 287.0
            [max_supply] => 21000.0
            [last_updated] => 1519152868
        )

)

If you want to get the first index ( $novoArray[0] ), use the command current :

$novoArray = current($novoArray);

So the result will be this:

Array
(
    [id] => A220
    [name] => Dipirona
    [symbol] => R$
    [rank] => 1
    [price_br] => 8.4
    [price_usd] => 2.0
    [total_supply] => 287.0
    [max_supply] => 21000.0
    [last_updated] => 1519152868
)
    
20.02.2018 / 20:36
1

Just use a forach to read the array I assume your array is called $ arr

<?php
    foreach($arr as $prod){
        echo $prod['id']
        // ai é so chamar a variavel $prod com o indice
    }
?>

Or if you want to directly access without looping

$arr[0]['id']; 
$arr[1]['id'];
    
20.02.2018 / 20:16