doubi12138 2017-09-29 14:49
浏览 61
已采纳

PHP阵列中的JSON解码数据

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条回答 默认 最新

  • douquan9826 2017-09-29 14:59
    关注

    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): ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败