Home > Enterprise >  How to access a key in a multiple array using php
How to access a key in a multiple array using php

Time:11-26

I want to output just the "status" key of the array below, but it's not working.

$array=array(
    [0] => array(
        [error] =>none 
        [response] => array( 
            [0] => array( 
                [status] => success
            )
        )
    ) 
    [1] =>  array(
        [error] =>failed 
        [response] => array( 
            [0] => array( 
                [status] => failed
            )
        )
    )
);

foreach ($array["status"] as $key => $value) {
    print '<br /> key: ' . $key . '  value: ' . $value;
}

My desired result should output status: success, status: failed

CodePudding user response:

There you go :

foreach ($array as $k => $item) { //loop over all array
    foreach($item['response'] as $key => $value) { //loop over all "response" indexes
        echo "status item $k : {$value['status']} <br>";
    }
}

CodePudding user response:

There are syntax errors in declaring array. You should not use [ ] for key, and you should use comma to separate array elements.

Here is the solution:

$array=array(
    '0' => array(
        'error' =>'none', 
        'response' => array( 
            0 => array( 
                'status' => 'success'
            )
        )
    ),
    '1' =>  array(
        'error' => 'failed', 
        'response' => array( 
            0 => array( 
                'status' => 'failed'
            )
        )
    )
);

foreach ($array as $key => $value) {    
    echo "status item" . $key . " : " . $value['response'][0]['status'] . "<br>";
}
  • Related