How to compare two multidimensional arrays by certain keys in each? - php

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);

Related

need to change number of rows of an array

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') );

Sorting a Multi-Dimensional Array by sum of object values in PHP

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',
),
),
)

PHP Echo from multidimensional arrays

I'm trying to echo the "name" variable from this array.
array(2) {
["error"] => bool(false)["response"] => array(8) {
["id"] => int(560277)["name"] => string(7)
"Jeff" ["avatar"] => string(55)
"https://etc.etc" ["joinDate"] => string(19)
"2015-09-21 16:47:53" ["steamID64"] => int(76521228272726998)
["groupName"] => string(6)
"Player" ["groupID"] => int(1)["permissions"] => array(2) {
["isGameAdmin"] => bool(false)["showDetailedOnWebMaps"] => bool(false)
}
}
}
I'm not sure how to access it, I've tried:
json->response->name;, but this won't work because this is an array not an object and json[0]["response"]["name"];
EDIT:
The array is coming from a json API, here is an example. https://api.truckersmp.com/v2/player/2
I am then converting that using
$json = (json_decode($tmpServer, true, JSON_BIGINT_AS_STRING));
i got it working on php fiddle like this
$arr = file_get_contents("https://api.truckersmp.com/v2/player/2");
$decoded = json_decode($arr,true);
echo $decoded["response"]["name"];

Sort Multidimensional Array By Searched Word

I need to sort a multidimensional array by a searched keyword.
My array is like below.
<?php
array(
array(
'name' => '11th-Physics',
'branch' => 'Plus One',
'college' => 'Plus One',
),
array(
'name' => 'JEE-IIT',
'branch' => 'Physics',
'college' => 'IIT College',
),
array(
'name' => 'Physics',
'branch' => 'Bsc Physics',
'college' => 'College of Chemistry',
),
array(
'name' => 'Chemical Engineering',
'branch' => 'Civil',
'college' => 'Physics Training Center',
),
array(
'name' => 'Physics Education',
'branch' => 'Mechanical',
'college' => 'TBR',
),
)
?>
I need to sort this array when search keyword is physics . And after Sorting i need the result like below.
NEEDED RESULT
<?php
array(
array(
'name' => 'Physics',
'branch' => 'Bsc Physics',
'college' => 'College of Chemistry',
),
array(
'name' => 'Physics Education',
'branch' => 'Mechanical',
'college' => 'TBR',
),
array(
'name' => '11th-Physics',
'branch' => 'Plus One',
'college' => 'Plus One',
),
array(
'name' => 'JEE-IIT',
'branch' => 'Physics',
'college' => 'IIT College',
),
array(
'name' => 'Chemical Engineering',
'branch' => 'Civil',
'college' => 'Physics Training Center',
),
)
?>
That is I need to sort the array first by the name which is exactly like the searched keyword. Then wildcard search in name. Then to the next key branch and same as above. Is there any php function to sort this array like my requirement. I have already checked asort, usort. But I didn't get result properly.
Just call this simple function I just created for your requirement, It works just fine :) change the priority order according to your need
function sortArray($array,$itemToSearch)
{
$sortedArray = array();
$priorityOrder = ['name','branch','college'];
foreach ($priorityOrder as $key)
{
foreach ($array as $i => $value)
{
if(strpos(strtolower($value[$key]), strtolower($itemToSearch)) === 0)
{
array_push($sortedArray, $value);
unset($array[$i]);
}
}
foreach ($array as $i => $value)
{
if(strpos(strtolower($value[$key]), strtolower($itemToSearch)) > 0)
{
array_push($sortedArray, $value);
unset($array[$i]);
}
}
}
return $sortedArray;
}
Here we go
So I started from the algorithm in this answer and modified it to fit your requirements. Since you have three different "priorities" to you sorting, we have to use some temporary variables to separate the elements we wish sorted.
// arrays used to separate each row based on the row where the word "Physics" is found
$searchName = array();
$searchBranch = array();
$searchCollege = array();
// arrays used later for array_multisort
$foundInName = array();
$foundInBranch = array();
$foundInCollege = array();
foreach ($var as $key => $row) {
if(strpos(strtolower($row['name']), 'physics') !== false) {
$searchName[$key] = $row['name'];
$foundInName[] = $row;
}
elseif(strpos(strtolower($row['branch']), 'physics') !== false) {
$searchBranch[$key] = $row['branch'];
$foundInBranch[] = $row;
}
elseif(strpos(strtolower($row['college']), 'physics') !== false) {
$searchCollege[$key] = $row['college'];
$foundInCollege[] = $row;
}
}
// Note: I use SORT_NATURAL here so that "11-XXXXX" comes after "2-XXXXX"
array_multisort($searchName, SORT_NATURAL, $foundInName); // sort the three arrays separately
array_multisort($searchBranch, SORT_NATURAL, $foundInBranch);
array_multisort($searchCollege, SORT_NATURAL, $foundInCollege);
$sortedArray = array_merge($foundInName, $foundInBranch, $foundInCollege);
Outputting $sortedArray using var_dump() gives something like:
array(5) {
[0]=> array(3) {
["name"]=> string(12) "11th-Physics"
["branch"]=> string(8) "Plus One"
["college"]=> string(8) "Plus One"
}
[1]=> array(3) {
["name"]=> string(7) "Physics"
["branch"]=> string(11) "Bsc Physics"
["college"]=> string(20) "College of Chemistry"
}
[2]=> array(3) {
["name"]=> string(17) "Physics Education"
["branch"]=> string(10) "Mechanical"
["college"]=> string(3) "TBR"
}
[3]=> array(3) {
["name"]=> string(7) "JEE-IIT"
["branch"]=> string(7) "Physics"
["college"]=> string(11) "IIT College"
}
[4]=> array(3) {
["name"]=> string(20) "Chemical Engineering"
["branch"]=> string(5) "Civil"
["college"]=> string(23) "Physics Training Center"
}
}
As you can see 11th-Physics comes out first. That is because the ASCII value of numbers is lower than that of letters. To fix this, modify the $search... arrays by prepending a high ASCII character before the string.
if(strpos(strtolower($row['name']), 'physics') !== false) {
// if the first character is a number, prepend an underscore
$searchName[$key] = is_numeric(substr($row['name'], 0, 1)) ? '_'.$row['name'] : $row['name'];
$foundInName[] = $row;
}
Which yields the following output:
array(5) {
[0]=> array(3) {
["name"]=> string(7) "Physics"
["branch"]=> string(11) "Bsc Physics"
["college"]=> string(20) "College of Chemistry"
}
[1]=> array(3) {
["name"]=> string(17) "Physics Education"
["branch"]=> string(10) "Mechanical"
["college"]=> string(3) "TBR"
}
[2]=> array(3) {
["name"]=> string(12) "11th-Physics"
["branch"]=> string(8) "Plus One"
["college"]=> string(8) "Plus One"
}
[3]=> array(3) {
["name"]=> string(7) "JEE-IIT"
["branch"]=> string(7) "Physics"
["college"]=> string(11) "IIT College"
}
[4]=> array(3) {
["name"]=> string(20) "Chemical Engineering"
["branch"]=> string(5) "Civil"
["college"]=> string(23) "Physics Training Center"
}
}
Try it here!

PHP Multidimensional Array with multiple array with same keys?

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']
];

Categories