简体   繁体   中英

How to get nth element of a multidimensional array in PHP?

I want to select the "RSI" from the first element only.

Array (json file):

{
"Technical": {
    "2019-01-11 15:30": {
        "RSI": "123"
    },
    "2019-01-11 14:30": {
        "RSI": "456"
    }
    "2019-01-11 14:30": {
        "RSI": "789"
    }
}

My php:

foreach ($json['Technical'] as $field => $value) {
 echo $value['RSI']; // Gives 123456789
}

I tried:

 echo $value[0]['RSI']; // Gives NULL

Break the loop with break; and it will only return the first item.

foreach ($json['Technical'] as $field => $value) {
 echo $value['RSI']; // Gives 123
 break;
}

If you want specific items then use a "$key" variable.

$key = 0;
foreach ($json['Technical'] as $field => $value) {
    if($key == 0 || $key ==1){  
        echo $value['RSI']; 
    }
    $key++;
}
//  123456

Change the if to suit your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM