Illegal string offset 'key' - php

I have this code:
// Champion name and splash art
$endpointChampion = file_get_contents("https://global.api.riotgames.com/api/lol/static-data/BR/v1.2/champion/".$championMastery."?api_key=MYKEY");
$jsonChampion = json_decode($endpointChampion, true);
foreach ($jsonChampion as $champion) {
if (isset($jsonChampion['key'])) {
$championKey = $champion['key'];
}
}
But this $championKey variable returns "o" and 3 warnings are prompted on screen:
Warning: Illegal string offset 'key' in E:\xampp\htdocs\riot\index.php on line 41
I also tried to validate the entry, using isset() but seems not work properly.
The $championMastery is retrieved here:
$endpointMastery = file_get_contents("https://br.api.riotgames.com/championmastery/location/BR1/player/8083198/champions?api_key=MYKEY");
$jsonMastery = json_decode($endpointMastery, true);
foreach ($jsonMastery as $mastery) {
$championMastery = $mastery['championId'];
$masteryLevel = $mastery['championLevel'];
}

You are getting error because API returns one dimensional array and $champion is string value in foreach ($jsonChampion as $champion). Following can be fix:
foreach ($jsonChampion as $champion) {
if (isset($jsonChampion['key'])) {
$championKey = $jsonChampion['key'];
}
}
BTW,
$jsonChampion is one dimensional Array so you can retrieve $championKey without writing foreach loop as follows:
if(is_array($jsonChampion) && isset($jsonChampion['key'])){
$championKey = $jsonChampion['key'];
}

Related

Accessing a specific nested value from Spotify Artists array

I am using jwilsson's spotify-web-api-php to return data from the Spotify API using PHP.
Also I'm using digitalnature's php-ref to return info about variables.
This is my (terrible) code:
// https://stackoverflow.com/questions/4345554/convert-a-php-object-to-an-associative-array
function objectToArray($r)
{
if (is_object($r)) {
if (method_exists($r, 'toArray')) {
return $r->toArray(); // returns result directly
} else {
$r = get_object_vars($r);
}
}
if (is_array($r)) {
$r = array_map(__FUNCTION__, $r); // recursive function call
}
return $r;
}
$session = new SpotifyWebAPI\Session(
'aaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbb'
);
$session->requestCredentialsToken();
$accessToken = $session->getAccessToken();
$str = $_POST['str'];
$str_length = strlen($_POST['str']);
$html = null;
$api = new SpotifyWebAPI\SpotifyWebAPI();
$api->setAccessToken($accessToken);
$search = $api->search('fugazi','artist');
$search_array = objectToArray($search);
r($search_array);
// loop through the results
foreach($search_array['artists']['items'] as $item) {
// artist name
$artist_name = $item['name'];
$html .= "<h2>$artist_name</h2>";
// genres
foreach($item['genres'] as $genre) {
$html .= " <span class='code'>$genre</span> ";
}
// $v2 = $item['images']['0']['height'];
// r($v2);
}
This is what the php-ref shows the $search_array to look like:
Or as plain text: https://0bin.net/paste/iPYfn2M6#Pt8l-a9i9el0TVnZsDTA8wlbe/t0CGSIsp4bds0IZyT
I would like to access the attributes for the first element in the images array for each artist returned.
I tried via this line:
$v2 = $item['images']['0']['height'];
But the following error was returned:
PHP Notice: Undefined offset: 0 in C:\Websites\spotify\search.php on line 68
PHP Notice: Trying to access array offset on value of type null in C:\Websites\spotify\search.php on line 68
I have searched around that error but I can't get my head around the correct syntax to use in this example.
Sorry for my lack of understanding.

Storing another array's values in an array using foreach

This is my code:
$videos_key = array();
foreach($result[$x]["videos_key"] as $videos_key )
{
$videos_key[] = $result[$x]["videos_key"];
}
print $videos_key;
Here $result[$x]["videos_key"]is an array, which have values. It is inside an forloop, so [$x] is an number like: 0,1,2,3...
I want to transfer it's value to $videos_key
Errors:
Warning: Invalid argument supplied for foreach()
2nd error
Notice: Array to string conversion
Invalid argument supplied for foreach()?? $result[$x]["videos_key"] is an array???
$videos_key = array();
if (is_array($result[$x]["videos_key"])){
foreach($result[$x]["videos_key"] as $key => $value )
{
array_push($videos_key,$value);
}
}else{
echo "no array";
}
echo print_r($videos_key, true);

SimpleXML expecting array error PHP

ok below is my code
<?php
// Last 10 Jobs
function last10IT(){
$xml = simplexml_load_file('http://www.cv-library.co.uk/cgi-bin/feed.xml?affid=101899');
$new_array = array();
//$limit = 5;
//$c = 0;
foreach ($xml->jobs->job as $job) {
// if ($limit == $c) {
// break;
// }
$jobref = $job->jobref;
$title = $job->title;
$date = $job->date;
$new_array[$jobref.$date] = array(
'jobref' => $jobref,
'date' => $date,
'title' => $title,
'salary' => $job->salary,
'location' => $job->location,
);
}
}
ksort($new_array);
$showl = 10;
$n = 0;
foreach ($new_array as $date => $listing) {
print $listing['title'] . PHP_EOL;
}
?>
All I want it to do is filter by category & display a max of 10 results
for example
IT
so is there a way I can pass the category value into the function that I want it to filter by
instead of having to replicate for each category
All I get is :
Warning: ksort() expects parameter 1 to be array, null given in
C:\wamp\www\RECRUITMENTFAIR\functions.php on line 28
Please help guys
It something SO simple causing this error but its driving me mad because I just cannot see it
it is relative simple: you try to use the variable $new_array out of scope:
it is defined within your last10IT() function, but the function ends after the first foreach.
you should either return the array and call the function to get the array or move the part with the ksort and the printing into the function, depending on your needs.
Also was having issues by not having the PHP Extension xmlrpc enabled !
what a tool !
Thats why i was getting failed to open half the time

Assigning values to associative array (multidimensional)

while($row = $champions_table_result->fetch_assoc()){
while($row3['Champion']==$row['Champion']){
$test[$row['Champion']]['General']['Change'][] =$row3['Stat_Change'];
$test[$row['Champion']]['General']['Type'][] = $row3['Stat_Change_Icon'];
}
foreach ($row as $column_name => $column) {
if ($column_name == 'Champion') {
continue; // These fields were already displayed above
}
if (!empty($column)) {
$test[$row['Champion']][$column_name] =$column;
while($row2['Champion']==$row['Champion']&&$row2['Spell_Type']
==$column_name&&!empty($row2['Spell_Change'])) {
$test[$row['Champion']][$column_name]['Change'][] = $spell_descriptions[ $champion_counter][$spell_counter][$change_counter];
$test[$row['Champion']][$column_name]['Type'][] = $spell_changes[
$champion_counter][$spell_counter][$change_counter];
$row2 = $spells_table_result->fetch_assoc();
}
}
}
}
To better showcase my problem here is an image with var_dump from $test - array http://i.imgur.com/xcox2df.png and next to Q W E it should show variable $column; I'm trying to achieve that in this line
$test[$row['Champion']][$column_name] =$column;
Without this line I get what I showed on imgur but with this line I get an error:
Warning: Illegal string offset 'Change' and Fatal error: Cannot use string offset as an array

Warning: Illegal offset type while create dyamic menu

I' am trying my best to create dynamic menu and submenu. While trying I got plenty errors, Was able to solve some errors.
This is the current errror message am getting
Warning: Illegal offset type in D:\xampp\htdocs\projects\xxxx.php on line 40
array(0) { }
This function loops an array and created UL LI Dynamically & Levels
function loop_section($array = array(), $section_parent_id = 0)
{
var_dump($array );
if (!empty($array[$section_parent_id])) {
echo '<ul>';
foreach ($array as $values) {
echo '<li>';
echo $values->section_name;
echo $values->section_id;
loop_section($array, $values->section_id);
echo '</li>';
}
echo '</ul>';
}
}
This function Query the database and gets the results
function fetch_sections()
{
global $db;
$array = array();
$query = $db->SELECT("SELECT * FROM sections");
$rows = $db->ROWS(); // Returns an error
$array[$rows];
loop_section($array);
}
Database Strucutre
This is the database structure
$array[$rows];
Should be:
$array[] = $rows;
Since $rows is also an array, it cannot be the key in an array. Also the line $array[$rows]; would do nothing, even if $rows was a valid variable to be an array key (int, string)

Categories