I have an array that looks like this...
array(3) {
[0]=>
array(1) {
[0]=>
array(1) {
["@attributes"]=>
array(1) {
["data"]=>
string(23) "football games on today"
}
}
}
[1]=>
array(1) {
[0]=>
array(1) {
["@attributes"]=>
array(1) {
["data"]=>
string(8) "football"
}
}
}
[2]=>
array(1) {
[0]=>
array(1) {
["@attributes"]=>
array(1) {
["data"]=>
string(14) "football today"
}
}
}
}
etc. Normally, I would just loop through this array to get the data that I need which would look like this...
$x=0;
foreach($array as $a){
echo $a[$x][0]['@attributes']['data'].'<br>';
$x++;
}
But, for some reason this very simple foreach loop will not output the data as I would expect. The loop returns nothing. I have add an
$x=0;
foreach($array as $d){
echo $d[$x][0]['@attributes']['data'].'<br>';
echo $x.'<br>';
$x++;
}
echo $x; line into the code, and it will echo the incremental x value, so I know if is looping through the array properly.
It has been a very long few days of coding, so maybe I am just burnt out and missing somethings really simple. But I am not seeing it. Thank you for any help. It is much appreciated.
</div>
If you do end up with deeply nested arrays you can gather the keys and values of the array 'leaves', by using array_walk_recursive:
<?php
$data =
[
[
[
'wanted' => 'foo'
],
],
[
[
'wanted'=> 'bar'
],
'dead'=>'parrot'
]
];
array_walk_recursive($data, function($v, $k) use (&$wanteds) {
if($k==='wanted')
$wanteds[]=$v;
});
var_export($wanteds);
Output:
array (
0 => 'foo',
1 => 'bar',
)
Note the conditional check on the leaf keys to only gather the attributes wanted.
You can then loop through the generated array easily.