I'm using an API my teacher made. And So far I'm able to get some information out of it.
But I need to get certain information into variables, so I can push it to my database. I decodes the information so far, en it looks like this:
Array
(
[0] => stdClass Object
(
[homeClub] => Roda JC
[awayClub] => Feyenoord
)
[1] => stdClass Object
(
[homeClub] => SC Cambuur
[awayClub] => Feyenoord
)
[2] => stdClass Object
(
[homeClub] => Heracles Almelo
[awayClub] => Feyenoord
)
And so on
But now I need to get both homeClub and awayClub each in a seperate variable. And im stuck.
If anyone could help me, it would be great. This is my code so far:
$methods = array(
'wedstrijden?club=Feyenoord'
);
$method = $methods[0];
$data = json_decode(file_get_contents($url . $method));
print_rr($data);
function print_rr($data){
echo '<pre>';
print_r($data);
echo '</pre>';
}
<?php
foreach($data as $row) {
echo "home club is: " . $row->homeClub;
echo "away club is: " . $row->awayClub;
}
you could also decode the json as associative array:
change $data = json_decode(file_get_contents($url . $method));
to $data = json_decode(file_get_contents($url . $method), true);
and iterate using:
<?php
foreach($data as $row) {
echo "home club is: " . $row['homeClub'];
echo "away club is: " . $row['awayClub'];
}
Oh, and don't let SO'ers do your homework :P
Related
If I have the following array
$arrays = $cdo->rows();
Array
(
[0] => Array
(
[0] => what is the name of you ?
[1] => Reham
)
[1] => Array
(
[0] => Where did you came from ?
[1] => earth
)
)
Using PHP language how can i print this like a question and answer
My try since Iam not good in PHP was
foreach ($arrays as $arr){
//print_r($arr);
foreach (arr as $a){
echo $a . "<br />";
}
}
But results like
what is the name of you ?
Reham
Where did you came from ?
earth
So I'm unable to know where is the question and where is the answer, as I'm going to insert it into database so am i supposed to something like
foreach ($arrays as $arr){
//print_r($arr);
foreach (arr as $q => $a){
echo "Question : " . $q . " | Answer : " . $a . "<br />";
}
}
I don't think I fully understood what you want. Is this what you are looking for?
$array = [
[
'what is the name of you ?',
'Reham'
],
[
'Where did you came from ?',
'earth'
]
];
foreach($array as $arr) {
echo $arr[0] . '<br>' . $arr[1] . '<br>';
}
Let me know if this is what you want.
Your array is not really good to deal with, it's only an indexed array, you should use a multidimensional.
But you can just use indexes :
foreach ($arrays as $arr) {
echo $arr[0]; // question
echo $arr[1]; // answer
}
Whenever I run this code through the SalesForce PHP api, it fails with err:Notice: Trying to get property of non-object
$query ="SELECT accountId,Status,Id,Service_Account_DMKT__r.name,(select Activity_Type__c from Tasks) from case where Owner.Name ='" . $name . "' AND CreatedDate = THIS_MONTH AND Record_type_name__c='Performance Reviews' AND status NOT IN ('')";
$response = $mySforceConnection->query($query);
$queryResult = new QueryResult($response);
foreach($queryResult->records as $case){
//for ($queryResult->rewind(); $queryResult->pointer < $queryResult->size; $queryResult->next()) {
$callCounter = 0;
$emailCounter = 0;
$accountId = $case->current()->accountId;
$accountName=$case->current()->Service_Account_DMKT__r->Name;
$caseId= $case->current()->Id;
if($case->any['Tasks']->records) {
$counter=0;
foreach($case->any['Tasks']->records as $record) {
$taskRecord = $record->any;
if (strpos($taskRecord, 'Call - Outbound') !== false) {
$callCounter++;
} else {
$emailCounter++;
}
$counter++;
}
}
echo '<p>AccountName=' . $accountName . '</p><p>CaseId=' . $caseId . '</p>';
echo '<p>' . $callCounter . ' Calls and ' . $emailCounter . ' emails';
echo'<hr>';
$index++;
}
print_r($case);
I know it is because of these three lines. I'm not stepping through the object correctly.
$accountId = $case->current()->accountId;
$accountName=$case->current()->Service_Account_DMKT__r->Name;
$caseId= $case->current()->Id;
But I'm not sure what to use instead of current(). Below is the response object from the SF API
stdClass Object
(
[type] => Case
[Id] => Array
(
[0] => 5000e00001J7L0pAAF
[1] => 5000e00001J7L0pAAF
)
[any] => Array
(
[0] => 00130000002bqXiAAIClosed - Contact Declined5000e00001J7L0pAAF
[Service_Account_DMKT__r] => stdClass Object
(
[type] => Account
[Id] =>
[any] => brinsoncorsicanafordfd
)
[Tasks] => stdClass Object
(
[done] => 1
[queryLocator] =>
[records] => Array
(
[0] => stdClass Object
(
[type] => Task
[Id] =>
[any] =>
)
)
[size] => 1
)
)
)
I finally managed to fix it by converting the response back to another object
$query ="SELECT accountid,Status,Id,Service_Account_DMKT__r.name,(select Activity_Type__c,subject from Tasks) from case where Owner.Name ='" . $SFName . "' AND CreatedDate = THIS_MONTH AND Record_type_name__c='Performance Reviews' AND status NOT IN ('')";
$response = $mySforceConnection->query($query);
$queryResult = new QueryResult($response);
foreach($queryResult->records as $case){ //For every record within $queryResult
$callCounter = 0; //Set up our task counters
$emailCounter = 0;
$sObject = new SObject($case); //turn $case back into a SObj to easy step thru
$accountId= $sObject->AccountId; //Pull AccountId from $sObject
$accountName=$sObject->Service_Account_DMKT__r->Name;
$caseId=$sObject->Id;
$caseStatus=$sObject->Status;
if(!isset($sObject->queryResult)) { //Check if there are any tasks on the record, otherwise we'll get an error
$callCounter=0; //if there are no tasks, set counters to 0
$emailCounter=0;
}else{
$counter=0;
foreach($case->any['Tasks']->records as $record) { //for each task in the $case
$taskObject = new SObject($record); //Turn $record into taskObject so we can step through it.
$taskType = $taskObject->Activity_Type__c; //Pull the activity type out of TaskObject
if($taskType == "Call - Outbound"){ //Calling $taskType actually allows us to compare the obj to a string, where as going through this in an array format would not!
$callCounter++; //increase counter if the taskType is a call
} else {
$emailCounter++;
}
}
}
echo '<p>AccountName=' . $accountName . '</p><p>AccountID=' . $accountId . '</p><p>CaseId=' . $caseId . '</p><p>CaseStatus=' . $caseStatus . '</p>';
echo '<p>' . $callCounter . ' Calls and ' . $emailCounter . ' emails';
echo'<hr>';
}
I wanted to print the name of the coin (obtained from a JSON response of a site) + "test" when the page is loaded; the problem is that only "test" is printed as if it did not find the name of the coin.
PHP code:
<?php
$coinbase = "https://api.coinmarketcap.com/v1/ticker";
$array = array("/bitcoin","/ethereum");
find();
function find(){
$coin = file_get_contents($GLOBALS["coinbase"].$array[1]);
$coin = json_decode($coin, TRUE);
$v = $coin['name']."test";
echo $v;
}
?>
JSON structure:
[
{
id: "bitcoin-cash",
name: "Bitcoin Cash",
symbol: "BCH",
rank: "4",
price_usd: "1042.72",
price_btc: "0.114721",
24h_volume_usd: "462221000.0",
market_cap_usd: "17742232718.0",
available_supply: "17015338.0",
total_supply: "17015338.0",
max_supply: "21000000.0",
percent_change_1h: "1.59",
percent_change_24h: "-4.49",
percent_change_7d: "-14.31",
last_updated: "1520950752"
}
]
If I try like this I got the answer. I've printed the $coin for your clear understanding How can you easily access 2D array with its index 0 here.
function find()
{
$coinbase = "https://api.coinmarketcap.com/v1/ticker";
$array = array("/bitcoin","/ethereum");
$coin = file_get_contents($coinbase.$array[1]);
$coin = json_decode($coin, TRUE);
//printing only for debug purpose
print '<pre>';
print_r($coin);
print '<pre>';
$v = $coin[0]['name']."test";
echo $v;
}
find();
Output:
Printing it just for your clear understanding why I used $coin[0]['name'] index to get the name from 2D $coin array.
Array
(
[0] => Array
(
[id] => ethereum
[name] => Ethereum
[symbol] => ETH
[rank] => 2
[price_usd] => 687.193
[price_btc] => 0.0760364
[24h_volume_usd] => 1696390000.0
[market_cap_usd] => 67457446384.0
[available_supply] => 98163757.0
[total_supply] => 98163757.0
[max_supply] =>
[percent_change_1h] => -0.63
[percent_change_24h] => -2.36
[percent_change_7d] => -16.98
[last_updated] => 1520955853
)
)
This is what you want
Ethereumtest
N.B: Please note here the comment of https://stackoverflow.com/users/4265352/axiac carefully
$array is not accessible in function find(). Read about variable scope
in PHP then forget everything about $GLOBALS or global
As per comment:
$coinbase = "https://api.coinmarketcap.com/v1/ticker";
$array = array("/bitcoin","/ethereum");
function find(){
global $coinbase;
global $array;
$coin = file_get_contents($coinbase.$array[1]);
$coin = json_decode($coin, TRUE);
print '<pre>';
print_r($coin);
$v = $coin[0]['name']."test";
echo $v;
}
find();
Try:
$coin = file_get_contents($GLOBALS["coinbase"].$array[1]);
$coin = json_decode($coin, TRUE);
$v = $coin[0]['name']."test";
echo $v;
This json is an array of ojects so you should access first the index of the array and then, the property of the object.
EDIT
$coin = file_get_contents("https://api.coinmarketcap.com/v1/ticker/ethereum");
Try to hardcode the url to test it.
I have the customer details in the following format
How do i fetch the customer id is '5' from the output.
json_decode(array)
Result:
stdClass Object (
[5] => stdClass Object (
[email] => siddareddy.vishnuvardhanreddy#gmail.com
[firstname] => vishnu
[lastname] => siddareddy
)
)
You can cast it to an array and then get the first key:
$key = key( (array) $result_object );
$array = json_decode($json, true);
foreach ($array as $key => $value)
{
echo $key; //or use $value array to get the rest of its info
}
Please note that your first line cannot yield the second line as output. The first line should return an array, while the second code block is an object.
You can loop through all keys and values of your Array/Object and get the '5' that way:
foreach( $decodedjson as $key => $val ) {
#Key is: 5
echo "Key is: {$key}";
#Val['firstname'] is: vishnu
echo "Val['firstname'] is: {$val['firstname']}";
}
You can access the numeric property like this
<?php
$data = array(
"5" => array(
'email' => 'siddareddy.vishnuvardhanreddy#gmail.com',
'firstname' => 'vishnu',
'lastname' => 'siddareddy'
)
);
$json = json_encode($data);
$obj = json_decode($json);
var_dump($obj->{5}->email);
$obj->{5}->email, this the trick.
If you want to invert the array from id to that array from say, email to id:
$result = json_decode($array, true);
// Change email to something else if you want another key
$inversecopy = array_flip(array_map(function($val) { return $val['email']; }, $result));
Example in phpfiddle
I need some help reading the values from multidimension arrays. The array looks like below.
Array
(
[translations] => Array
(
[0] => Array
(
[translatedText] => fantasma
[detectedSourceLanguage] => en
)
)
)
I tried the following, but kept on getting blanks. Any help be appreciated?
foreach($item as $translations)
{
foreach($row['0'] as $k)
{
echo $k['translatedText'];
echo $k['detectedSourceLanguage'];
}
}
When working with foreach loops, you want to call the array you plan on iterating over with the following syntax:
foreach($array as $variable){ }
Array being the array you plan on going through, and the variable being the variable you are planning to call it as within the foreach.
More information on foreach loops can be found at PHP:foreach
With that said, try the code below:
$data = array(
"translations" => array(
array("translatedText" => "fantasma",
"detectedSourceLanguage" => "en"
)
)
);
echo "<pre>";
echo print_r($data);
echo "</pre>";
foreach($data["translations"] as $translation) {
echo $translation['translatedText'] . "<br />";
echo $translation['detectedSourceLanguage'] . "<br />";
}
//Or, if the $data variable will be holding multiple translation arrays:
foreach($data as $d) {
foreach($d as $translation){
echo $translation['translatedText'];
echo $translation['detectedSourceLanguage'];
}
}
Try this:
foreach ($item['translations'] as $translation) {
echo $translation['translatedText'];
echo $translation['detectedSourceLanguage'];
}
See DEMO
Change your code to below :
$test = Array(
"translations" => Array (
"0" => Array (
"translatedText" => "fantasma",
"detectedSourceLanguage" => "en"
)
)
);
foreach ($test as $translations) {
foreach ($translations as $k) {
echo $k["translatedText"];
echo "<br/>";
echo $k["detectedSourceLanguage"];
}
}
This should work.
Follow this for more info about array : http://php.net/manual/en/language.types.array.php
The issue is that you are not defining the $row variable. The good news is that you don't need it.
You can simply do this:
foreach($item as $translations => $values)
{
foreach($values as $k)
{
echo $k['translatedText']."\n";
echo $k['detectedSourceLanguage'];
}
}