0

Trying to access data that has been JSON decoded in PHP, loop through the array and print it in my view, but I keep getting an illegal string offset error for the part of the array I'm trying to access.

When I var-dump the array, I can see the data that has been pulled from the api, but for some reason this error keeps getting thrown when I try to access it. Code below (using codeigniter):

model

function getAllPokemon() {
    $url = 'http://pokeapi.co/api/v2/pokemon/?limit=151';
    $response = file_get_contents($url);
    $allPokemonData = json_decode($response, true);
    return $allPokemonData;
}

controller

public function index()
{
    $data['thepokemon'] = $this->pokemon_model->getAllPokemon();
    $this->load->view('template/header');
        $this->load->view('home', $data);
    $this->load->view('template/footer');
}

view

<?php foreach($thepokemon as $poke): ?>
    <p><?php echo $poke['name']; ?></p>
<?php endforeach; ?>

If I do something along the lines of:

<?php foreach($thepokemon as $poke): ?>
    <p><?php echo $poke[2]['name']; ?></p>
<?php endforeach; ?>

It will print the name for that index in the array, but the error is still thrown.

Any help would be great! Thanks in advance.

example of var_dump:

array(4) { ["count"]=> int(811) ["previous"]=> NULL ["results"]

1 Answer 1

1

You have this:

array(4) { 
    ["count"]=> int(811) 
    ["previous"]=> NULL 
    ["results"]=> array(151) { 
        [0]=> array(2) { 
            ["url"]=> string(36) "https://pokeapi.co/api/v2/pokemon/1/" 
            ["name"]=> string(9) "bulbasaur" 
        } 
        [1]=> array(2) { 
            ["url"]=> string(36) "https://pokeapi.co/api/v2/pokemon/2/" 
            ["name"]=> string(7) "ivysaur" 
        } 

So the loop should be:

<?php foreach($thepokemon['results'] as $poke): ?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks dude! I can't believe I missed that - feel like an idiot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.