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

报告相同问题?

悬赏问题

  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。