简体   繁体   中英

PHP - Foreach loop only echoing first letter of string

I have an array that looks like this:

array(1) { 
    ["brookybear"]=> array(5) { 
        ["id"]=> int(20217894) 
        ["name"]=> string(10) "Brookybear" 
        ["profileIconId"]=> int(603) 
        ["summonerLevel"]=> int(30) 
        ["revisionDate"]=> float(1397388011000) 
    } 
}

when i var_dump(); it. I'm trying to use a foreach loop to take the "name" value out of it. However, when I echo it, I only get "B" as the output, and not the full Brookybear.

Here is my foreach loop:

$url="APIURL";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
$array = json_decode($result, true);
foreach($array['brookybear'] as $champs)
{
echo $champs['name'];
}

Looks like you're looping on the 'brookybear' item instead of the parent array.

If you want to see all the name s of all the $champ s:

$array = json_decode($result, true);
foreach($array as $champs)
{
    echo $champs['name'];
}

or more clearly:

$champions = json_decode($result, true);
foreach($champions as $champ)
{
    echo $champ['name'];
}

Why do you use loop to get the value? If I am doing this, I will simply write:

<?php
if ( isset( $array['brookybear']['name'] ) ) {
    echo $array['brookybear']['name'];
}

If first character is only display in string, you know what is the reason i now,

make sure array variable name is not same in your above script

. example

$my_var = "My name is umair";

and below you same use this variable for array

$my_var[0] = "My name is umair";

now if you echo array var it will show only first letter in output is "M" simply change the array variable than it will be working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM