I am having trouble trying to decode the following json response from api-football using PHP. My knowledge of PHP is very limited so please bear with me.
A sample of the vardump is as follows:
array(1) {
["api"]=>
array(2) {
["results"]=>
int(10)
["fixtures"]=>
array(10) {
[0]=>
array(18) {
["fixture_id"]=>
int(932017)
["league_id"]=>
int(4633)
["league"]=>
array(4) {
["name"]=>
string(10) "Pro League"
["country"]=>
string(12) "Saudi-Arabia"
["logo"]=>
string(52) "https://media.api-sports.io/football/leagues/307.png"
["flag"]=>
string(42) "https://media-3.api-sports.io/flags/sa.svg"
}
["event_date"]=>
string(25) "2023-01-22T20:30:00+03:00"
["event_timestamp"]=>
int(1674408600)
["firstHalfStart"]=>
NULL
["secondHalfStart"]=>
NULL
["round"]=>
string(19) "Regular Season - 14"
["status"]=>
string(11) "Not Started"
["statusShort"]=>
string(2) "NS"
["elapsed"]=>
int(0)
["venue"]=>
string(11) "Mrsool Park"
["referee"]=>
NULL
["homeTeam"]=>
array(3) {
["team_id"]=>
int(2939)
["team_name"]=>
string(8) "Al-Nassr"
["logo"]=>
string(53) "https://media-3.api-sports.io/football/teams/2939.png"
}
["awayTeam"]=>
array(3) {
["team_id"]=>
int(2934)
["team_name"]=>
string(10) "Al-Ettifaq"
["logo"]=>
string(51) "https://media.api-sports.io/football/teams/2934.png"
}
["goalsHomeTeam"]=>
NULL
["goalsAwayTeam"]=>
NULL
["score"]=>
array(4) {
["halftime"]=>
NULL
["fulltime"]=>
NULL
["extratime"]=>
NULL
["penalty"]=>
NULL
}
}
What I am trying basically is printing the fixture for "homeTeam" and "awayTeam". But I am definitely not getting it correctly. Here is my code :
<?php
$url = "https://api-football-v1.p.rapidapi.com/v2/fixtures/team/2939/next/10?rapidapi-key={API-Key}";
$request = wp_remote_get( $url );
if ( ! is_wp_error( $request ) ) {
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body, true );
}
echo $data["fixtures"][0]["league"]["name"];
echo $data["fixtures"][0]["homeTeam"]["teamname"];
echo $data["fixtures"][0]["awayTeam"]["teamname"];
?>
Here is dump from varexport()
array (
'api' =>
array (
'results' => 10,
'fixtures' =>
array (
0 =>
array (
'fixture_id' => 932017,
'league_id' => 4633,
'league' =>
array (
'name' => 'Pro League',
'country' => 'Saudi-Arabia',
'logo' => 'https://media-3.api-sports.io/football/leagues/307.png',
'flag' => 'https://media-3.api-sports.io/flags/sa.svg',
),
'event_date' => '2023-01-22T20:30:00+03:00',
'event_timestamp' => 1674408600,
'firstHalfStart' => NULL,
'secondHalfStart' => NULL,
'round' => 'Regular Season - 14',
'status' => 'Not Started',
'statusShort' => 'NS',
'elapsed' => 0,
'venue' => 'Mrsool Park',
'referee' => NULL,
'homeTeam' =>
array (
'team_id' => 2939,
'team_name' => 'Al-Nassr',
'logo' => 'https://media.api-sports.io/football/teams/2939.png',
),
'awayTeam' =>
array (
'team_id' => 2934,
'team_name' => 'Al-Ettifaq',
'logo' => 'https://media-3.api-sports.io/football/teams/2934.png',
),
'goalsHomeTeam' => NULL,
'goalsAwayTeam' => NULL,
'score' =>
array (
'halftime' => NULL,
'fulltime' => NULL,
'extratime' => NULL,
'penalty' => NULL,
),
),
You aren't accessing the data properly to retrieve the team names, please try this instead:
echo $data["api"]["fixtures"][0]["league"]["name"];
echo $data["api"]["fixtures"][0]["homeTeam"]["team_name"];
echo $data["api"]["fixtures"][0]["awayTeam"]["team_name"];
Related
I have this array in indice.php, included into my page.php, is an array exported from the table "indice" of my db.
<?php
$indice = array(
array('id' => '1','def' => 'Admin'),
array('id' => '2','def' => 'Utente'),
array('id' => '31','def' => 'Aldwich Vertigos'),
array('id' => '32','def' => 'Celtic Newcastle'),
array('id' => '91','def' => 'Serie A'),
array('id' => '92','def' => 'Serie B'),
array('id' => '93','def' => 'Premier League'),
array('id' => '110','def' => 'Argentina'),
array('id' => '431','def' => 'Brisbane Road'),
array('id' => '432','def' => 'Kingstone Park'),
array('id' => '120','def' => 'Belgio') ); ?>
And my array is in this way:
array(416) {
[0]=>
array(2) {
["id"]=>
string(1) "1"
["def"]=>
string(5) "Admin"
}
[1]=>
array(2) {
["id"]=>
string(1) "2"
["def"]=>
string(6) "Utente"
}
[2]=>
array(2) {
["id"]=>
string(2) "31"
["def"]=>
string(16) "Aldwich Vertigos"
...etc...
then i print this:
<?php
include("functions.php");
include("auth.php");
include("db.php");
include("indice.php");
$indiceok = $indice['2']['def'];
echo $indiceok;
?>
'''
Well... My $indiceok stamps 'Aldwych Vertigos', but how could i obtain that $indiceok using the ID (2) stamps "Utente"?
I appreciate too a string which change my array in an array like this, using ID to identify my array selections:
array(416) {
[1]=>
array(2) {
["id"]=>
string(1) "1"
["def"]=>
string(5) "Admin"
}
[2]=>
array(2) {
["id"]=>
string(1) "2"
["def"]=>
string(6) "Utente"
}
**[31]**=>
array(2) {
["id"]=>
string(2) "31"
["def"]=>
string(16) "Aldwich Vertigos"
Many thanks and sorry for my question, i'm sure it's probably very easy to resolve, but i don't know how i can
You are looking for array_column.
By default it isolates a column in a multidimensional array but if you use the third argument you can make an array associative.
$yourarray = array_column($yourarray, Null, "id");
This will only work if id is unique.
If it's not unique, meaning you have two 31, the last subarray will be kept and the first will be truncated.
See result of your array here: https://3v4l.org/CJcJL
Alternatively, of your array is static you can just assign the keys manually in the code:
$indice = array(
"1" => array('id' => '1','def' => 'Admin'),
"2" => array('id' => '2','def' => 'Utente'),
"31" => array('id' => '31','def' => 'Aldwich Vertigos'),
"32" => array('id' => '32','def' => 'Celtic Newcastle'),
"91" => array('id' => '91','def' => 'Serie A'),
"92" => array('id' => '92','def' => 'Serie B'),
"93" => array('id' => '93','def' => 'Premier League'),
"110" => array('id' => '110','def' => 'Argentina'),
"431" => array('id' => '431','def' => 'Brisbane Road'),
"432" => array('id' => '432','def' => 'Kingstone Park'),
"120" => array('id' => '120','def' => 'Belgio') );
I have the below multi dimensional array of products. Each array is a pair of products that make a product set, I need to order the multi dimensional array by the total price of each product set.
array(4) {
[0]=>
array(2) {
["product1"]=>
object(stdClass)#5075 (2) {
["product_id"]=>
string(4) "9416"
["price"]=>
string(6) "110.00"
}
["product2"]=>
object(stdClass)#5077 (2) {
["product_id"]=>
string(4) "9431"
["price"]=>
string(6) "100.00"
}
}
[1]=>
array(2) {
["product1"]=>
object(stdClass)#5065 (2) {
["product_id"]=>
string(4) "1254"
["price"]=>
string(6) "75.00"
}
["product2"]=>
object(stdClass)#5067 (2) {
["product_id"]=>
string(4) "9431"
["price"]=>
string(6) "62.00"
}
}
[2]=>
array(2) {
["product1"]=>
object(stdClass)#5055 (2) {
["product_id"]=>
string(4) "9416"
["price"]=>
string(6) "45.00"
}
["product2"]=>
object(stdClass)#5057 (2) {
["product_id"]=>
string(4) "9431"
["price"]=>
string(6) "50.00"
}
}
[3]=>
array(2) {
["product1"]=>
object(stdClass)#5045 (2) {
["product_id"]=>
string(4) "9416"
["price"]=>
string(6) "60.00"
}
["product2"]=>
object(stdClass)#5047 (2) {
["product_id"]=>
string(4) "9431"
["price"]=>
string(6) "25.00"
}
}
}
I need to sort the multi-dimensional array by the total sum of product1 + product2 in each array in ascending order. For example [1] should be above [0] as 75+62 is less than 110 +100.
If anyone can help me with this it would be greatly appreciated.
You can use usort() for this purpose:-
function comparePrice($a,$b)
{
$a_price = $a['product1']->price + $a['product2']->price;
$b_price = $b['product1']->price + $b['product2']->price;
if ($a_price ==$b_price) return 0;
return ($a_price<$b_price)? -1:1;
}
usort($array,'comparePrice');
A hardcoded working example:- https://3v4l.org/mTfu6
You need to use user-defined sorting
http://php.net/manual/en/function.usort.php
usort($products, function($a, $b) {
$prodA = $a['product1']['price'] + $a['product2']['price'];
$prodB = $b['product1']['price'] + $b['product2']['price'];
if($prodA == $prodB) return 0;
return ($prodA < $prodB) ? -1 : 1;
});
The php7+ "spaceship operator" (aka three-way-comparison operator) makes the syntax with usort() as clean and brief as possible.
Code: (Demo)
$array = [
[
"product1" => (object) ["product_id" => "9416", "price"=>"110.00"],
"product2" => (object) ["product_id"=>"9431", "price"=>"100.00"]
],
[
"product1" => (object) ["product_id" => "1254", "price"=>"75.00"],
"product2" => (object) ["product_id"=>"9431", "price"=>"62.00"]
],
[
"product1" => (object) ["product_id" => "9416", "price"=>"45.00"],
"product2" => (object) ["product_id"=>"9431", "price"=>"50.00"]
],
[
"product1" => (object) ["product_id" => "9416", "price"=>"60.00"],
"product2" => (object) ["product_id"=>"9431", "price"=>"25.00"]
]
];
usort($array, function($a, $b) {
return $a['product1']->price + $a['product2']->price <=> $b['product1']->price + $b['product2']->price;
});
var_export($array);
Output:
array (
0 => // sum = 85.00
array (
'product1' =>
(object) array(
'product_id' => '9416',
'price' => '60.00',
),
'product2' =>
(object) array(
'product_id' => '9431',
'price' => '25.00',
),
),
1 => // sum = 95.00
array (
'product1' =>
(object) array(
'product_id' => '9416',
'price' => '45.00',
),
'product2' =>
(object) array(
'product_id' => '9431',
'price' => '50.00',
),
),
2 => // sum = 137.00
array (
'product1' =>
(object) array(
'product_id' => '1254',
'price' => '75.00',
),
'product2' =>
(object) array(
'product_id' => '9431',
'price' => '62.00',
),
),
3 => // sum = 210.00
array (
'product1' =>
(object) array(
'product_id' => '9416',
'price' => '110.00',
),
'product2' =>
(object) array(
'product_id' => '9431',
'price' => '100.00',
),
),
)
I'm able to retrieve metrics information for included metrics however for custom metrics, for example CPUUtilization on a per/instance basis, I cannot get the info. I'm not sure if I'm using the correct NameSpace, or perhaps I need to include additional information in the Dimensions field. Anyone know how to do this?
Here is my code:
<?php
date_default_timezone_set('America/New_York');
require 'vendor/autoload.php';
use Aws\CloudWatch\CloudWatchClient;
$cloudWatchClient = CloudWatchClient::factory(array(
'profile' => 'my_profile',
'region' => 'us-east-1',
));
$dimensions = array(
array('Name' => 'InstanceId', 'Value' => 'i-0c0f546e4d1ef25e1'),
array('Name' => 'ImageId', 'Value' => 'ami-9cdee48b'),
array('Name' => 'AutoScalingGroupName', 'Value' => 'lc-wordpress-asg'),
);
$cpuResult = $cloudWatchClient->getMetricStatistics(array(
'Namespace' => 'AWS/EC2',
'MetricName' => 'CPUUtilization',
'Dimensions' => $dimensions,
'StartTime' => strtotime('-5 minutes'),
'EndTime' => strtotime('now'),
'Period' => 300,
'Statistics' => array('Average'),
));
var_dump($cpuResult);
$memoryResult = $cloudWatchClient->getMetricStatistics(array(
'Namespace' => 'Linux System',
'MetricName' => 'MemoryUtilization',
'Dimensions' => $dimensions,
'StartTime' => strtotime('-5 hours'),
'EndTime' => strtotime('now'),
'Period' => 60,
'Statistics' => array('Average'),
));
var_dump($memoryResult);
?>
Running this code produces the following output. As you can see CPUUtilization returns the desired results however MemoryUtilization returns an empty array.
[ec2-user#ip-10-0-52-163 php-sdk]$ php get-cloudwatch-metrics.php
object(Guzzle\Service\Resource\Model)#100 (2) {
["structure":protected]=>
NULL
["data":protected]=>
array(3) {
["Datapoints"]=>
array(0) {
}
["Label"]=>
string(14) "CPUUtilization"
["ResponseMetadata"]=>
array(1) {
["RequestId"]=>
string(36) "63dc311e-bdaf-11e6-8143-f96eefa160b8"
}
}
}
object(Guzzle\Service\Resource\Model)#102 (2) {
["structure":protected]=>
NULL
["data":protected]=>
array(3) {
["Datapoints"]=>
array(0) {
}
["Label"]=>
string(17) "MemoryUtilization"
["ResponseMetadata"]=>
array(1) {
["RequestId"]=>
string(36) "63dec890-bdaf-11e6-b04d-0707ed181fab"
}
}
}
Note, I'm using the typical AWS custom metric Perl scripts to send custom metrics to CloudWatch.
* * * * * ~/aws-scripts-mon/mon-put-instance-data.pl --mem-util --mem-used --mem-avail --disk-space-util --disk-path=/ --from-cron --aggregated --auto-scaling
I figured it out. A quick check of my custom metric instance scripts that put metrics to CloudWatch show a namespace of "System/Linux", however in the CloudWatch Console it displays "Linux System". Switching the code to System/Linux produces the expected results!
$dimensions = array(
array('Name' => 'InstanceId', 'Value' => 'i-0c0f546e4d1ef25e1'),
);
$memoryResult = $cloudWatchClient->getMetricStatistics(array(
'Namespace' => 'System/Linux',
'MetricName' => 'MemoryUtilization',
'Dimensions' => $dimensions,
'StartTime' => strtotime('-5 minutes'),
'EndTime' => strtotime('now'),
'Period' => 60,
'Statistics' => array('Average'),
));
var_dump($memoryResult);
Output below:
[ec2-user#ip-10-0-52-163 php-sdk]$ php get-cloudwatch-metrics.php
object(Guzzle\Service\Resource\Model)#100 (2) {
["structure":protected]=>
NULL
["data":protected]=>
array(3) {
["Datapoints"]=>
array(5) {
[0]=>
array(3) {
["Average"]=>
string(16) "50.1385233069785"
["Unit"]=>
string(7) "Percent"
["Timestamp"]=>
string(20) "2016-12-10T23:07:00Z"
}
[1]=>
array(3) {
["Average"]=>
string(16) "38.5987663771093"
["Unit"]=>
string(7) "Percent"
["Timestamp"]=>
string(20) "2016-12-10T23:08:00Z"
}
[2]=>
array(3) {
["Average"]=>
string(16) "41.5588687016341"
["Unit"]=>
string(7) "Percent"
["Timestamp"]=>
string(20) "2016-12-10T23:09:00Z"
}
[3]=>
array(3) {
["Average"]=>
string(16) "45.4270517993215"
["Unit"]=>
string(7) "Percent"
["Timestamp"]=>
string(20) "2016-12-10T23:10:00Z"
}
[4]=>
array(3) {
["Average"]=>
string(16) "46.4784461685095"
["Unit"]=>
string(7) "Percent"
["Timestamp"]=>
string(20) "2016-12-10T23:06:00Z"
}
}
["Label"]=>
string(17) "MemoryUtilization"
["ResponseMetadata"]=>
array(1) {
["RequestId"]=>
string(36) "07c17abc-bf2e-11e6-a0ce-0f6cd308d7b2"
}
}
}
I used to have same problem,
Problem was in dimensions (I should use ClusterName)
$dimensions = array(array('Name' => 'ClusterName', 'Value' => env('AWS_CLUSTER_NAME')));
$metrics = $cloudWatch->GetMetricStatistics(['Namespace' => 'AWS/ECS',
'MetricName' => "MemoryUtilization",
'Period' => 60,
'Dimensions' => $dimensions,
'StartTime' => strtotime('-24 hours'),
'EndTime' => strtotime('now'),
'Statistics' => array('Maximum', 'Minimum', 'Average')]);
I am unable to retrieve the item using filterExpression using logical and or or in Dyanamodb php using aws sdk. can any any one provide the code with the correct syntax to retrieve the item satisfying both the condition.
$scan_response = $dynamodb->scan(array(
'TableName' => $tableName,
'ExpressionAttributeValues' => [
':val1' => ['S' => '20'],
':val2' => ['S' => 'ajay'],
'FilterExpression' => 'age = :val1 AND name = :val2'
]));
i am getting error that
filterExpression must be a associative array
Thanks in advance
try this
$scan_response = $dynamodb->scan(array(
'TableName' => $tableName,
'ExpressionAttributeValues' => [
':val1' => ['S' => '20'],
':val2' => ['S' => 'ajay']],
'FilterExpression' => 'age = :val1 AND name = :val2'
));
badly placed closing ] creates
array(2) {
["TableName"]=>
string(3) "..."
["ExpressionAttributeValues"]=>
array(3) {
[":val1"]=>
array(1) {
["S"]=>
string(2) "20"
}
[":val2"]=>
array(1) {
["S"]=>
string(4) "ajay"
}
["FilterExpression"]=>
string(28) "age = :val1 AND name = :val2"
}
}
instead of required
array(3) {
["TableName"]=>
string(3) "..."
["ExpressionAttributeValues"]=>
array(2) {
[":val1"]=>
array(1) {
["S"]=>
string(2) "20"
}
[":val2"]=>
array(1) {
["S"]=>
string(4) "ajay"
}
}
["FilterExpression"]=>
string(28) "age = :val1 AND name = :val2"
}
I have two multidimensional arrays of the same structure.
Like this:
array(2) {
[0] =>
array(9) {
'id' =>
string(5) "44994"
'ersatzteil_id' =>
string(3) "120"
'lang' =>
string(6) "name2_tag2"
'title' =>
string(12) "Seitentüren"
'alias' =>
string(12) "seitentueren"
'content' =>
string(1610) "LOREM ISPUM BLALABLBL"
'on_main' =>
string(1) "0"
'disabled' =>
string(1) "1"
'short_text' =>
NULL
}
[1] =>
array(9) {
'id' =>
string(5) "44996"
'ersatzteil_id' =>
string(3) "122"
'lang' =>
string(6) "name1_tag1"
'title' =>
string(7) "Spoiler"
'alias' =>
string(7) "spoiler"
'content' =>
string(1513) "SOME OTHER RANDOM TEXT"
'on_main' =>
string(1) "0"
'disabled' =>
string(1) "0"
'short_text' =>
NULL
}
}
What I need to do is I need to compare first array with the second one.
I have to compare them by keys ersatzteil_id and content , and I find that they have same content I need to store element from first array in another new array, that wasn't existing before.
For example I need something like this, but more efficient:
if(array1[20]['ersatzteil_id'] == array2[145]['ersatzteil_id']
&& array1[20]['content'] == array2[145]['content']){
array3 = array1[20];
}
Try this code:-
$result = [];
foreach($array1 as $arr1){
foreach($array2 as $arr2){
if(($arr1['id'] == $arr2['id']) && ($arr1['ersatzteil_id'] == $arr2['ersatzteil_id'])){
$result[] = $arr1;
}
}
}
echo '<pre>'; print_r($result);