Search code examples
phparraysforeacharray-key

Read key of array two dimension


I try to read some keys of an array like

array(3) {

["poste5:"]=> array(3) { [0]=> string(7) "APPLE:" [1]=> string(5) "demo1" [2]=> string(5) "demo2" }

["services:"]=> array(4) { [0]=> string(9) "orange" [1]=> string(5) "demo3" [2]=> string(5) "demo4" [3]=> string(5) "demo1" }

["essai:"]=> array(2) { [0]=> string(6) "sd" } }

I try to read this name : poste5 , services , essai

If i use :

foreach ($this->aliasRead as $key => $value){

echo array_keys($this->aliasRead[$key]);
}

I have : Array()

But if i use :

foreach (array_keys($this->aliasRead) as $key => $value2) {
       echo $value2;
}

I have poste5 , services , essai

I try to use with this loop foreach ($this->aliasRead as $key => $value){ because i have another traitment after. How to collect this key of my first loop in this loop foreach ($this->aliasRead as $key => $value){ ?


Solution

  • You already have what you want here:

    foreach ($this->aliasRead as $key => $value){
        echo $key; // key of the value in the array
        print_r($value); // value of $this->aliasRead[$key] which in turn is another array
    }
    

    Edit: The reason your second loop works is because of this: array_keys($this->aliasRead[$key]) returns a new array containing the keys of the old array as its values. So $myNewArray = array_keys($this->aliasRead[$key]) is the same as $myNewArray = array('poste5','services','essai'). So, when you loop over this new array like this:

    foreach ($myNewArray as $key => $value2) {
        echo $value2;
    }
    

    $value2 contains your values, which are the keys of your first array, and $key will be 0, 1 and 2 after each step through the loop.