PHP - Foreach loop only echoing first letter of string - php

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 names of all the $champs:
$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

Related

how to save output result outside the loop

How to use a php variable outside the loop
how to save output result outside the loop
this variable $jsonrs
this is the result I want it outside the loop
"1""1.jpg""2""2.jpg""3""3.jpg""4""4.jpg"
$url = 'https://hentaifox.com/gallery/58769/';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
preg_match_all('!<img class="lazy no_image" data-src="(.*?)"!', $result, $manga_name);
$items = array();
foreach ($manga_name[1] as $key => $manganm) {
$imag_manga = str_replace('t.jpg','.jpg',$manganm);
$imagerep = 'https:'.$imag_manga;
$filename = basename($imagerep);
$imag_num = str_replace('.jpg','',$filename);
$array_name = array($imag_num => $filename);
$json1 = json_encode($imag_num);
$json2 = json_encode($filename);
$jsonrs = $json1.$json2;
print_r($jsonrs);
}
Your end result in $jsonrs is a bit unusual, I (am assuming) that you want to JSON encode the list of images, if so then use $items to keep a list of each image and then json_encode() this list after the loop...
foreach ($manga_name[1] as $key => $manganm) {
$filename = basename($manganm);
$imag_num = str_replace('t.jpg','',$filename);
$items[$imag_num] = $filename;
}
echo json_encode($items);
will give you
{"1":"1t.jpg","2":"2t.jpg","3":"3t.jpg","4":"4t.jpg"}

Delete an element from curl-json

I can get data from a website with CURL and I can convert this data to json.
I want to remove an element from json.
Output:
{
"test":{
"numbers":
[
"1",
"27",
"32",
"1",
"94",
"1",
"8"
]
}
}
I want to remove "1" from my json. How can I do that? Thank you for your help.
my code:
<?php
function Curlconnect($start,$end,$website) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $website);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$website = curl_exec($ch);
preg_match_all('#'.$start.'(.*?)'.$end.'#si',$website,$ver);
return $ver[1];
curl_close($ch);
}
function nt($start,$bit,$data,$a) {
preg_match_all('#'.$start.'(.*?)'.$bit.'#si',$data,$ver);
return $ver[1];
}
$url = 'http://www.url.com';
$getdata = Curlconnect('<h4','h4>',$url);
$jsonData = ["data"];
$jsonData["numbers"] = [];
for ($a=0; $a<count($getdata); $a++) {
$printdata = nt('>','</',$getdata[$a],$a);
$jsonData["test"]["numbers"][] = $printdata[0];
}
echo json_encode($jsonData);
?>
You can use array_search() to look for a value in an array (your $jsonData["test"]["numbers"] array), and use unset() to remove the value from the array.
Because there are multiple "1" values, and array_search() only returns the first key found, you'll need to use a while loop to ensure you find all the values to remove.
function remove_value_from_array ($val, $array)
{
while ( ($key = array_search($array, $val)) !== false)
{
unset($array[$key]);
}
return $array;
}
$jsonData["test"]["numbers"] = remove_value_from_array($jsonData["test"]["numbers"], "1");
Edit: I've remembered a simpler way - and a way that allow you to search for multiple values. You can simply use array_diff() to search for values, and remove them.
// Remove a single value of "1"
$jsonData["test"]["numbers"] = array_diff($jsonData["test"]["numbers"], array(1));
// Remove multiple values, of "1", "2", "5", and the word "test"
$jsonData["test"]["numbers"] = array_diff($jsonData["test"]["numbers"], array(1, 2, 5, "test"));

PHP - Variable returns NULL, but it shouldn't?

So I am trying to make, code will get certain parts matching ID's from the JSON array.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response, true);
//-------------------------------------
$invIndexes = [];
foreach($json->rgInventory as $index){
$invIndexes = $index;
}
//-------------------------------------
$makearray = (array)$invIndexes;
for($id = 0;$id < count($invIndexes);$id++){
$index = $makearray[$id];
$item = $json->rgDescriptions[$json->rgInventory[$index]->classid + "_" + $json->rgInventory[$index]->instanceid];
if($item->tradeable != 1){
continue;
}
$ItemName = $item->market_hash_name;
}
var_dump($ItemName);
Here's the JSON: http://pastebin.ca/3591035
The $ItemName return's NULL but it shouldn't (At least I think that). Maybe someone can spot the mistake what I've been doing here :/
If you are you using true in json decode $json = json_decode($response, true);, then it will return an associative array, so you can access the value form array simply like this $json['rgInventory'] not $json->rgInventory
To create $invIndexes array use this:
$invIndexes = array();
foreach($json['rgInventory'] as $index){
$invIndexes[] = $index['id'];
}
Here you will get $invIndexes the in your for loo you are again using $json->rgDescriptions to access values, change this to $json['rgInventory'] and for all other values use array keys like this $json['rgInventory']['index']['class']
No need of this $makearray = (array)$invIndexes; directly use $invIndexes
$index = $invIndexes[$id];
$item = $json['rgDescriptions'][$json['rgInventory'][$index]['classid']."_".$json['rgInventory'][$index]['instanceid']];
Another mistake is that in your $item there is not any key tradeable, its tradable an use like this
if($item['tradeable'] != 1){
continue;
}
$ItemName = $item['market_hash_name'];
At last var_dump($ItemName);
The second argument true to json_decode tells it to convert JSON objects into PHP associative arrays rather than PHP objects. But using syntax like $json->rgDescriptions requires $json to be an object; for an array it should be $json['rgDescriptions'].
So either change all your uses of $json to use array syntax, or remove the true argument from json_decode. The latter should be easier.
Also, this line:
$invIndexes = $index;
should be:
$invIndexes[] = $index;
But you could replace that loop with just:
$invIndexes = $json->rgInventory;

How to use foreach statement to loop through Faroo json search engine results?

I do not quite understand the parameters I need to use for a foreach statement to work on this query.
Any idea why this foreach does not work? sample faroo query:
http://www.faroo.com/api?q=%27elephants%27&start=1&length=10&l=en&src=web&f=json&jsoncallback=mycallback&key=y3EVs8B2ntbxXrmZWpBTDBueayA_&rlength=0
<?php
$ch = curl_init();
if ($_POST['query'])
{
$query = urlencode("'{$_POST['query']}'");
$fullUri = 'http://www.faroo.com/api?q='.$query.'&start=1&length=10&l=en&src=web&f=json&jsoncallback=mycallback&key=y3EVs8B2ntbxXrmZWpBTDBueayA_&rlength=0';
curl_setopt($ch, CURLOPT_URL, $fullUri);
echo $fullUri;
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$data=curl_exec($ch);
$js = json_decode($data);
$i=0;
foreach ($js -> results as $item)
{
$Faroo[$i] = "<a href=\"{$item->url}\">
{$item->title}</a>faroo
<p>$item->kwic}</p>";
$i++;
}
echo $Faroo[3];
}
Remove the jsoncallback parameter from the request... what's being returned isn't valid JSON. Removing this parameter fixes the issue.
I'd check into json_last_error if you run into issues with JSON in the future- it can be very helpful!

PHP Outputting results based on greater than/less than from JSON

I am trying to get this script to output results based on a greater than/less than script. When I run this script all it does it output the first line in the text file. Any suggestions as to what I am missing?
<?php
$lines = file('unique.txt'); // Reads the file with the list of user numbers
$timestamp = time(); // Defines time for below renaming
foreach ($lines as $usernumber) { // Loops line by line
$link = 'http://backpack.tf/api/IGetUsers/v2/?&steamids=' . $usernumber . '&format=json';
$json = file_get_contents($link); // Reads link (this ^)
$data = json_decode($json); // Defines decode as json
if (!empty($data)) {
$profiles = array(); //init array so we can use $profiles[] later
foreach ($data->response->players as $player) { // Loop thrugh all the players
$player2 = $player->backpack_value;
if ($player2 < 9999999) { // Check the backpack_value
$profiles[] = $player; // Assign the required players to a new array
var_dump($profiles); // Dump the array to browser for debugning
$fh = fopen("final." . $timestamp . ".txt", 'a') or die("can't open file"); // Opens final.txt to write in
fwrite($fh, $usernumber); // Writes the parsed results to final.txt
} //closes if $playtime
} //closes foreach $data
} //closes if !empty
else {
echo $data;
}
} //closes foreach $lines
?>
Unique.txt contains
76561197992831594
76561197992707820
76561197992146126
76561197992694522
76561197992707820
76561197992831594
JSON Example
{
"response": {
"success": 1,
"current_time": 1369685515,
"players": {
"0": {
"steamid": "76561197992831594",
"success": 1,
"backpack_value": 47.97,
"backpack_update": 1369683750,
"name": "WesFox13",
"notifications": 0
}
}
}
}
Okay There is two fundamental problems.
The fopen call needs to move outside of the loop.
the file call has an annoying habit of keeping the trailing newline. When you are building up your url you should use trim($usernumber) to get rid of it.
Here is an update with those two things in place.
<?php
$lines = file('unique.txt'); // Reads the file with the list of user numbers
$timestamp = time(); // Defines time for below renaming
$fh = fopen("final." . $timestamp . ".txt", 'a') or die("can't open file"); // Opens final.txt to write in
foreach ($lines as $usernumber) { // Loops line by line
$link = 'http://backpack.tf/api/IGetUsers/v2/?&steamids=' . trim($usernumber) . '&format=json';
$json = file_get_contents($link); // Reads link (this ^)
$data = json_decode($json); // Defines decode as json
print_r($json);
if (!empty($data)) {
$profiles = array(); //init array so we can use $profiles[] later
foreach ($data->response->players as $player) { // Loop thrugh all the players
$player2 = $player->backpack_value;
if ($player2 < 9999999) { // Check the backpack_value
$profiles[] = $player; // Assign the required players to a new array
var_dump($profiles); // Dump the array to browser for debugning
fwrite($fh, $usernumber); // Writes the parsed results to final.txt
} //closes if $playtime
} //closes foreach $data
} //closes if !empty
else {
echo $data;
}
} //closes foreach $lines
I've done this with CURL and it works too.
The code:
$lines = array('76561197992831594','76561197992707820','76561197992146126');
$timestamp = time(); // Defines time for below renaming
foreach ($lines as $usernumber) { // Loops line by line
$link = 'http://backpack.tf/api/IGetUsers/v2/?&steamids=' . $usernumber . '&format=json';
$json = curl_download($link); // Reads link (this ^)
$data = json_decode($json); // Defines decode as json
if (!empty($data)) {
$profiles = array(); //init array so we can use $profiles[] later
foreach ($data->response->players as $player) { // Loop thrugh all the players
$player2 = $player->backpack_value;
if ($player2 < 9999999) { // Check the backpack_value
$profiles[] = $player; // Assign the required players to a new array
var_dump($profiles); // Dump the array to browser for debugning
file_put_contents("final." . $timestamp . ".txt", $usernumber);
} //closes if $playtime
} //closes foreach $data
} //closes if !empty
else {
echo $data;
}
}
curl download function:
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Set a referer
curl_setopt($ch, CURLOPT_REFERER, "http://www.google.pl");
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla Firefox/1.0");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
Output:
array(1) { [0]=> object(stdClass)#102 (6) { ["steamid"]=> string(17) "76561197992831594" ["success"]=> int(1) ["backpack_value"]=> float(47.97) ["backpack_update"]=> int(1369683750) ["name"]=> string(8) "WesFox13" ["notifications"]=> int(0) } } array(1) { [0]=> object(stdClass)#106 (6) { ["steamid"]=> string(17) "76561197992707820" ["success"]=> int(1) ["backpack_value"]=> float(59.78) ["backpack_update"]=> int(1369689171) ["name"]=> string(10) "Alexsutton" ["notifications"]=> int(0) } } array(1) { [0]=> object(stdClass)#98 (6) { ["steamid"]=> string(17) "76561197992146126" ["success"]=> int(1) ["backpack_value"]=> float(36181.59) ["backpack_update"]=> int(1369689000) ["name"]=> string(25) ":HIT: Bobo the Monkey Boy" ["notifications"]=> int(0) } }
My suggestion to you is to use CURL when you want to download something from Web. Moreover use file_get_contents() and file_put_contents() syntax is short and they do the same and they are easier to use.

Categories