How to accesss php associative array values?

My var_dump $data looks something like this. I am looping through user names and I need to get the value "username1"

$key returns an integer when I loop through $key=>$value.

array(1) {   ["username1"]=>   array(2) {     ["enum"]=>;     array(1) {       [1]=>;       array(1) {         ["label"]=>;         bool(true)         }       }     ["total"]=>;     int(20)   } 

Edit 1: here’s my code
assignment

foreach($keys as $key){             $this->data[] = array_fill_keys($keys,$this->getData($key, date('Y'))); } 

function getData

private function getData($key, $year)     {         return isset($this->datas[$key][$year]) ? $this->datas[$key][$year] : array();     } 

loop to access value

foreach($this->data as $kpi=>$value) {             var_dump($kpi); } 

Solution :

The problem was here

$this->data[] = array_fill_keys($keys,$this->getData($key, date('Y'))); 

The data[] array had integer indexes.

iterating through $this->data[1] gives me the key values.

But However, I feel there is a better way to handle this, Could someone please help me to improve this?

Add Comment
1 Answer(s)

sorry for writing comment as an answer earlier. Question was not clear.

Basically the type of associative array you trying to do should look like something like this.

‘$keys = array( "username1" =>array( “enum” => (int)3, “label” => true, “total => (int)20 ));’

So the value of “username1” is going to be arrays of “enum” and “label”

Lastly the as $key array must be written like ‘$key[‘enum’] $key[‘label’] $key[‘total’] right after the foreach command

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.