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') );
Related
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"];
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've been trying multiple things and for the life of me can not get this to work. I'm beginning to think it maybe isn't possible at this point.
So I have a SOAP API I'm sending this array too. Below is the code I currently have that works, but does not send the multiple values. It just uses the last one as it overwrite the previous.
Looking at this thread, what I'm doing should work?
$my_array['sn'] = "234234232";
$my_array['arrayparams'] = array(
'Param' => array( 'Name' => 'sending_key', 'Value' => 'blah',),
'Param' => array( 'Name' => 'sending_key2', 'Value' => '2',),
);
$my_array['push'] = true;
$my_array['endsession'] = false;
returns:
array(4) {
["sn"]=>
string(12) "234234232"
["arrayparams"]=>
array(1) {
["Param"]=>
array(2) {
["Name"]=>
string(61) "sending_key2"
["Value"]=>
string(1) "2"
}
}
["push"]=>
bool(true)
["endsession"]=>
bool(false)
}
I'm just having a time getting it to send this instead:
array(4) {
["sn"]=>
string(12) "234234232"
["arrayparams"]=>
array(2) {
["Param"]=>
array(2) {
["Name"]=>
string(61) "sending_key"
["Value"]=>
string(1) "blah"
}
["Param"]=>
array(2) {
["Name"]=>
string(61) "sending_key2"
["Value"]=>
string(1) "2"
}
}
["push"]=>
bool(true)
["endsession"]=>
bool(false)
}
The 'Param' array is very strict and has to have this value, I can not change to 'Param2' to get it to work. Thanks in advanced!
can you do this?
$my_array['arrayparams'] = array(
array('Param' => array( 'Name' => 'sending_key', 'Value' => 'blah',)),
array('Param' => array( 'Name' => 'sending_key2', 'Value' => '2',)),
);
The problem is you can't have the key 'Param' set in more than one key.
You would need to define 'Param' as an actual array, instead of as multiple keys within in array.
like so...
$my_array['Param'] = [
['Name' => 'sending_key', 'Value' => 'blah'],
['Name' => 'sending_key2', 'Value' => '2']
];
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);
Combining A array and B array and want the result show below
EDITED
a = {
[0]=> array(2) {
["pid"]=> string(1) "1"
["val1"]=> string(1) "1"
}
[1]=> array(2) {
["pid"]=> string(2) "12"
["val1"]=> string(1) "1"
}
[2]=> array(2) {
["pid"]=> string(2) "13"
["val1"]=> string(2) "79"
}
}
b = {
[0]=> array(2) {
["pid"]=> string(1) "1"
["val2"]=> string(1) "1"
}
[1]=> array(2) {
["pid"]=> string(2) "12"
["val2"]=> string(1) "1"
}
[2]=> array(2) {
["pid"]=> string(2) "13"
["val2"]=> string(2) "79"
}
[3]=> array(2) {
["pid"]=> string(2) "61"
["val2"]=> string(1) "1"
}
[4]=> array(2) {
["pid"]=> string(2) "62"
["val2"]=> string(2) "24"
}
}
Need help.
If this is coming from a data source, see if there's a way you can do this outside of PHP (e.g. MySQL's JOIN).
If PHP is your only answer, then below is a solution. Note that I changed the values of val1 and val2 so it was a bit more distinguishable.
You must have some sort of grouping constraint, which is configurable in the script below via $groupByKey. Judging by the common occurrence of PID, I assumed this as the subject key.
Also, if you have more than two arrays all following a similar schema (I have commented out $c as an example), you simply add more arguments to array_merge.
The idea is to keep merging each item in the cumulative list by using a fixed key as a "pointer," if you will.
<?php
$a = array(
array('pid' => 1, 'val1' => 'alpha'),
array('pid' => 3, 'val1' => 'bravo'),
array('pid' => 4, 'val1' => 'charlie')
);
$b = array(
array('pid' => 3, 'val2' => 'delta'),
array('pid' => 5, 'val2' => 'echo'),
array('pid' => 1, 'val2' => 'foxtrot'),
array('pid' => 8, 'val2' => 'golf')
);
/*
$c = array(
array('pid' => 3, 'val3' => 'hotel'),
array('pid' => 5, 'val1' => 'india'),
array('pid' => 1, 'val3' => 'juliette'),
array('pid' => 8, 'val3' => 'kilo')
);
*/
$groupByKey = 'pid'; // this becomes the fixed key
$merged = array_merge($a,$b); // array_merge($a,$b,$c); // cumulative container of all items in every subject array
$result = array(); // the result will be stored here, e.g. a temporary "table"
foreach ( $merged as $item ) { // $merged is essentially a table of subjects and $item is each row
if ( !isset($result[$item[$groupByKey]]) ) { // if we haven't come across this key yet
$result[$item[$groupByKey]] = array(); // initialize it
}
$result[$item[$groupByKey]] = array_merge($result[$item[$groupByKey]],$item); // consolidate all the cells for this row, later duplicate keys will cause values to be replaced
}
$result = array_values($result); // normalize the result keys, for the view they should increment rather than represent the group-by subjects
var_dump($result); // let's see how we did
?>
Provides:
array (size=5)
0 =>
array (size=3)
'pid' => int 1
'val1' => string 'alpha' (length=5)
'val2' => string 'foxtrot' (length=7)
1 =>
array (size=3)
'pid' => int 3
'val1' => string 'bravo' (length=5)
'val2' => string 'delta' (length=5)
2 =>
array (size=2)
'pid' => int 4
'val1' => string 'charlie' (length=7)
3 =>
array (size=2)
'pid' => int 5
'val2' => string 'echo' (length=4)
4 =>
array (size=2)
'pid' => int 8
'val2' => string 'golf' (length=4)