PHP数组中的JSON解码数据

时间:2017-09-29 14:49:45

标签: php arrays json codeigniter

尝试访问已在PHP中进行JSON解码的数据,循环遍历数组并在我的视图中打印它,但是我仍然在尝试访问的数组部分中遇到非法的字符串偏移错误。

当我对数组进行var转储时,我可以看到从api中提取的数据,但由于某种原因,当我尝试访问它时,这个错误会一直被抛出。下面的代码(使用codeigniter):

模型

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

控制器

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

视图

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

如果我按照以下方式做某事:

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

它将在数组中打印该索引的名称,但仍会抛出错误。

任何帮助都会很棒!提前谢谢。

var_dump的例子:

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

1 个答案:

答案 0 :(得分:1)

你有这个:

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" 
        } 

所以循环应该是:

<?php foreach($thepokemon['results'] as $poke): ?>
相关问题