Exception or error:
I’m trying to do something I’ve never tried before: reading from APIs, and using the returned values in my website. To do this I need to read from multi-dimensional arrays in PHP.
See below the result I am getting from the API callback, when I run the following lines of code:
$tempContents = json_decode($data, true);
echo '<pre'; print_r($tempContents); echo '</pre';
Results:
Array (
[data] = Array
(
[boards] = Array
(
[0] = Array
(
[columns] = Array
(
[0] = Array
(
[title] = Name
)
[1] = Array
(
[title] = note
)
[2] = Array
(
[title] = notes2
)
[3] = Array
(
[title] = Status
)
)
)
)
)
[account_id] = xxxxxxx
)
So that’s great, I can see the information there; however, I’m not sure about how to construct a foreach function to retrieve individual values. For example; the name of the second title value.
How to solve:
You can do this in 2 way
using foreach()
directly:-
foreach($tempContents['data']['boards'][0]['columns'] as $title){
echo $title['title'].PHP_EOL;
}
Or using array_column()
along with foreach()
:
$finalArray = array_column($tempContents['data']['boards'][0]['columns'],'title');
foreach($finalArray as $title){
echo $title.PHP_EOL;
}
Sample Output:- https://3v4l.org/4ERqd