Join 2 multidimensional array - php

$items = array(
array(
'id' => 0,
'name' => 'Simple Sword',
'type' => 'weapon',
'price' => 200,
'value1' => 5,
'value2' => 10,
'value3' => 0,
'value4' => 0,
'value5' => 0
),
array(
'id' => 1,
'name' => 'Iron Sword',
'type' => 'weapon',
'price' => 500,
'value1' => 0,
'value2' => 0,
'value3' => 0,
'value4' => 0,
'value5' => 0
)
);
$inventory = array(
array(
'item' => 0,
'slot' => 1,
'value1' => 0,
'value2' => 0,
'value3' => 0,
'value4' => 0,
'value5' => 0,
'equipped' => 0
),
array(
'item' => 1,
'slot' => 2,
'value1' => 0,
'value2' => 0,
'value3' => 0,
'value4' => 0,
'value5' => 0,
'equipped' => 1
)
);
What I need is to join these 2 multidimensional arrays, or take the values, keys etc from the "Items" array and put it in the Inventory array where the "item" id matches the id from the Items array. Similiar to a INNER JOIN statement in SQL. How? I can't figure it out.
Secondly, I am trying to print out the $inventory array, I tried the following, but It didn't work:
foreach ($inventory as $a) {
foreach ($a as $b) {
echo $b['item'];
}
}
It gives me no output.

a little help with your second problem:
foreach ($inventory as $a => $b) {
echo $b['item'];
}
}

As for first question Zulkhaery Basrul gave good answer. I would also consider putting break statement if relation is one-to-one:
if($val['item'] == $items[$key]['id']) {
$newarr[] = array_merge($items[$key],$val);
break;
}
As for second question:
foreach ($inventory as $invKey => $aInventoryItem) {
echo $aInventoryItem['item'] . "\n";
}

I think you can just do this in order to echo the item from inventory:
foreach($inventory as $inv) {
echo $inv['item'];
}

foreach($inventory as $key=>$val)
{
if($val['item'] == $items[$key]['id'])
{
$newarr[] = array_merge($items[$key],$val);
}
}
check $newarr[] using print_r($newarr), here the output :
Array
(
[0] => Array
(
[id] => 0
[name] => Simple Sword
[type] => weapon
[price] => 200
[value1] => 0
[value2] => 0
[value3] => 0
[value4] => 0
[value5] => 0
[item] => 0
[slot] => 1
[equipped] => 0
)
[1] => Array
(
[id] => 1
[name] => Iron Sword
[type] => weapon
[price] => 500
[value1] => 0
[value2] => 0
[value3] => 0
[value4] => 0
[value5] => 0
[item] => 1
[slot] => 2
[equipped] => 1
)
)
Second question, to print out the $inventory array:
foreach ($inventory as $a)
{
echo $a['item'];
echo $a['slot'];
echo $a['value1'];
//...etc
}

I believe this function is what you're looking for:
// Join Arrays on Keys
function array_join($original, $merge, $on) {
if (!is_array($on)) $on = array($on);
foreach ($merge as $right) {
foreach ($original as $index => $left) {
foreach ($on as $from_key => $to_key) {
if (!isset($original[$index][$from_key])
|| !isset($right[$to_key])
|| $original[$index][$from_key] != $right[$to_key])
continue 2;
}
$original[$index] = array_merge($left, $right);
}
}
return $original;
}
Usage for your scenario:
print_r(array_join($items, $inventory, array('id' => 'item')));
I've asked the community for help with optimizing the LEFT JOIN version of the function here (the only differences are $remove unset and array_merge): How can I optimize my array_join (simulates a LEFT JOIN) function?

Related

Remove some keys from an array inside another array in PHP (Laravel)

How to remove some keys from an array inside another array in PHP?
I have this structure:
array (
0 =>
array (
'num' => '123',
'nome' => 'test 001'
'pontos' => 68,
'data_status' => '03/09/2021 10:05',
'uuid_status' => '69450ea451ae11ea85ca309c23d3a0ed'
),
1 =>
array (
'num' => '345',
'nome' => 'test 002'
'pontos' => 120,
'data_status' => '27/08/2021 15:46',
'uuid_status' => '3cbf4fd15d5411ea86956eef5d66cb13',
),
)
and need to return something like this:
array (
0 =>
array (
'num' => '123',
'nome' => 'test 001'
'pontos' => 68
),
1 =>
array (
'num' => '345',
'nome' => 'test 002'
'pontos' => 120
)
)
I've seen some answers but they seem to be outdated, also i'm using Laravel, so it would help if someone point me out something from the framework and its equivalent in pure PHP
A simple foreach loop is a good starting point, note this will remove items from the original array, by using the reference & to the array rather than a normal simple copy. On the $val in the foreach ( $input as &$val){
$input = [
[
'num' => '123',
'nome' => 'test 001',
'pontos' => 68,
'data_status' => '03/09/2021 10:05',
'uuid_status' => '69450ea451ae11ea85ca309c23d3a0ed'
],[
'num' => '345',
'nome' => 'test 002',
'pontos' => 120,
'data_status' => '27/08/2021 15:46',
'uuid_status' => '3cbf4fd15d5411ea86956eef5d66cb13'
]
];
$remove = ['data_status','uuid_status'];
foreach ( $input as &$val){
foreach ($val as $k => $v) {
if ( in_array($k,$remove) ) {
unset( $val[$k]);
}
}
}
print_r($input);
RESULT
Array
(
[0] => Array
(
[num] => 123
[nome] => test 001
[pontos] => 68
)
[1] => Array
(
[num] => 345
[nome] => test 002
[pontos] => 120
)
)
Probably not the most concise, but it gets the job done:
$bad_keys = array('data_status', 'uuid_status');
$array = array (
0 =>
array (
'num' => '123',
'nome' => 'test 001',
'pontos' => 68,
'data_status' => '03/09/2021 10:05',
'uuid_status' => '69450ea451ae11ea85ca309c23d3a0ed',
),
1 =>
array (
'num' => '345',
'nome' => 'test 002',
'pontos' => 120,
'data_status' => '27/08/2021 15:46',
'uuid_status' => '3cbf4fd15d5411ea86956eef5d66cb13',
),
);
function traverse_array($array, $bad_keys) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = traverse_array($value, $bad_keys);
} else {
foreach ($bad_keys as $remove_me) {
if ($key == $remove_me) {
unset($array[$key]);
}
}
}
}
return $array;
}
print_r(traverse_array($array, $bad_keys));

Remove all values => 0 from array and reverse it

I am a PHP beginner and have the following problem that I completely get stuck. I have an array in this format
Array (
[date] => 0
[author] => 1
[categories] => 1
[tags] => 0
[comments] => 0
[readmore] => 0
)
Now I need to remove all items that are [value] => 0 from that array and get it in this format
Array (
[0] => author
[1] => categories
)
Any input in this is much appreciated.
use array_filter and then array_keys:
$array = array ( 'date' => 0, 'author' => 1, 'categories' => 1, 'tags' => 0, 'comments' => 0, 'readmore' => 0 );
$array = array_filter($array);
print_r(array_keys($array));
output
Array
(
[0] => author
[1] => categories
)
There is a function called array_search() out there. Assuming the only possible values are 0 and 1, you can just serach the whole array for this value:
$array = [
'date' => 0,
'author' => 1,
'categories' => 1,
'tags' => 0,
'comments' => 0,
'readmore' => 0
];
$new_array = array_flip(array_search(1, $array));
So print_r($new_array) will give you your desired result.
You can try something like this:
foreach($array as $item){
if($item == "0"){
unset($item);
}
}
Or some modification with using unset function.
This is also do the job...
$dataSource = array('data' => 0,
'author' => 1,
'categories' => 1,
'tags' => 0,
'comments' => 0,
'readmore' => 0,
);
$updatedDataList = array();
foreach ($dataSource as $key => $value) {
if($value !== 0) {
$updatedDataList[] = $key;
}
}
print_r($updatedDataList);
#savethegold you can save your gold like below :D
<?php
$Array1 = array("date" => 0, "author" => 1, "categories" => 1, "tags" => 0, "comments" => 0, "readmore" => 0 );
foreach ($Array1 as $key => $value) {
if($value == 0){
unset($Array1[$key]);
}
}
$finalArr = array_keys($Array1);
print_r($finalArr);
You can try following code
$yourArray = Array ("date" => 0,"author" => 1, "categories" => 1,"tags" => 0, "comments" => 0,"readmore" => 0 );
$removeZeroFromArray = array(0);
$desiredResult = array_diff($yourArray, $removeZeroFromArray);
echo"<pre>";
print_r(array_keys($desiredResult));
echo"</pre>";
Your output will be like
Array
(
[0] => author
[1] => categories
)
Alternate way should be
$desiredResult = array_filter($yourArray, function($a) { return ($a !== 0); });
Hope it helps!
<?php
$array = array ( 'date' => 0, 'author' => 1, 'categories' => 1, 'tags' => 0, 'comments' => 0, 'readmore' => 0 );
$resutl = [];
foreach($array as $k => $v)
{
if($v != 0)
$result[] = $k;
}
print_r($result);

php - how to sum values of the multidimensional array

how can I sum values of the key 'NILAI_ANGGARAN'? Note that NILAI_ANGGARAN key is dynamic.
array :
[1350] => Array
(
[495] => Array
(
[NILAI_ANGGARAN] => 11000000
[NILAI_PPN] => 1000000
[PFK] => 0
[TAPERUM] => 0
[LAIN_LAIN] => 0
[NILAI_PPH21] => 500000
[NILAI_PPH22] => 0
[NILAI_PPH23] => 0
[NILAI_PPH4_2] => 0
[DENDA] => 0
[NILAI_BERSIH] => 10500000
)
)
[1300] => Array
(
[488] => Array
(
[NILAI_ANGGARAN] => 15000000
[NILAI_PPN] => 1500000
[PFK] => 0
[TAPERUM] => 0
[LAIN_LAIN] => 0
[NILAI_PPH21] => 0
[NILAI_PPH22] => 450000
[NILAI_PPH23] => 300000
[NILAI_PPH4_2] => 0
[DENDA] => 0
[NILAI_BERSIH] => 15750000
)
)
I've tried solution from How to sum values of the array of the same key? but it getting this error.
Undefined offset: 1350
Update :
This is my desidred result :
Array
(
[NILAI_ANGGARAN] => 26000000
[NILAI_PPN] => 2500000
[PFK] => 0
[TAPERUM] => 0
[LAIN_LAIN] => 0
[NILAI_PPH21] => 500000
[NILAI_PPH22] => 450000
[NILAI_PPH23] => 300000
[NILAI_PPH4_2] => 0
[DENDA] => 0
[NILAI_BERSIH] => 26250000
)
And this is the code I use :
$bruto = array();
foreach($array as $data => $key) {
foreach($key as $k => $value) {
foreach($value as $v => $isi) {
$bruto[$k]+=$value;
}
}
}
print_r($bruto);
Can anyone help me with another solution?
Thx
You can try this
Array:
$multi_dimentional_array = array (
'1350' => array
(
'495' => array
(
'NILAI_ANGGARAN' => 11000000,
'NILAI_PPN' => 1000000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 500000,
'NILAI_PPH22' => 0,
'NILAI_PPH23' => 0,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 10500000
)
),
'1300' => array
(
'488' => array
(
'NILAI_ANGGARAN' => 15000000,
'NILAI_PPN' => 1500000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 0,
'NILAI_PPH22' => 450000,
'NILAI_PPH23' => 300000,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 15750000
)
)
);
Get sum values of the key 'NILAI_ANGGARAN' Code:
$NILAI_ANGGARAN_TOTAL = 0;
foreach( $multi_dimentional_array as $fkey=>$smarray )
{
foreach ($smarray as $skey => $value) {
// Empty check
if ( !empty( $value['NILAI_ANGGARAN'] ) ){
$NILAI_ANGGARAN_TOTAL += $value['NILAI_ANGGARAN'];
}
}
}
echo "Sum of NILAI_ANGGARAN is :{$NILAI_ANGGARAN_TOTAL}";
Result:Sum of NILAI_ANGGARAN is :26000000
Let's consider the multi-dimensional array to be $array.
You simply need to use nested loop here.
Try this:
$sum = 0;
foreach ($array as $arr) {
foreach ($arr as $a) {
$sum += $a['NILAI_ANGGARAN'];
}
}
echo $sum;
Hope this helps.
Peace! xD
You also need to check if value with index 'NILAI_ANGGARAN' exists, otherwise PHP shows undefined offset error!
<?php
$array = array (
'1350' => array
(
'495' => array
(
'NILAI_ANGGARAN' => 11000000,
'NILAI_PPN' => 1000000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 500000,
'NILAI_PPH22' => 0,
'NILAI_PPH23' => 0,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 10500000
)
),
'1300' => array
(
'488' => array
(
'NILAI_ANGGARAN' => 15000000,
'NILAI_PPN' => 1500000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 0,
'NILAI_PPH22' => 450000,
'NILAI_PPH23' => 300000,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 15750000
)
)
);
$sum = 0;
foreach($array as $key => $subarray)
{
foreach($subarray as $subsubarrray)
{
if(isset($subsubarrray['NILAI_ANGGARAN'])) //check if isset
$sum += $subsubarrray['NILAI_ANGGARAN'];
}
}
var_dump($sum);
you can use advance php for the same. Using RecursiveArrayIterator and RecursiveIteratorIterator it can be done easily:
$multi_dimentional_array = array (
'1350' => array
(
'495' => array
(
'NILAI_ANGGARAN' => 11000000,
'NILAI_PPN' => 1000000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 500000,
'NILAI_PPH22' => 0,
'NILAI_PPH23' => 0,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 10500000
)
),
'1300' => array
(
'488' => array
(
'NILAI_ANGGARAN' => 15000000,
'NILAI_PPN' => 1500000,
'PFK' => 0,
'TAPERUM' => 0,
'LAIN_LAIN' => 0,
'NILAI_PPH21' => 0,
'NILAI_PPH22' => 450000,
'NILAI_PPH23' => 300000,
'NILAI_PPH4_2' => 0,
'DENDA' => 0,
'NILAI_BERSIH' => 15750000
)
)
);
$sum = 0;
$k_value = 'NILAI_ANGGARAN';
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($multi_dimentional_array));
foreach ($iterator as $key => $value) {
if($key == $k_value){
$sum +=$value;
}
}
echo "SUM of $k_value is $sum";
Output
SUM of NILAI_ANGGARAN is 26000000
use this code :
$sum_arr = array();
foreach($main as $m_item){
foreach($sub as $s_item){
foreach($s_item as $skey => $value){
$sum_arr[$skey] += $value;
}
}
}
use this code it will in $sum_arr is array of all element and its also in array format
try this it will work 100% :)

Extract a row by value from php array

This is my array:
Array (
[0] => Array ( [SocketID] => 1 [SocketName] => Name [SocketDecimal] => 0 [SocketHex] => 00 [SocketAtt] => 1 [Category] => 1 [Value] => 100 [Procentage] => 0 )
[1] => Array ( [SocketID] => 2 [SocketName] => Name2 [SocketDecimal] => 50 [SocketHex] => 32 [SocketAtt] => 1 [Category] => 1 [Value] => 800 [Procentage] => 0 )
[2] => Array ( [SocketID] => 3 [SocketName] => Name3 [SocketDecimal] => 100 [SocketHex] => 64 [SocketAtt] => 1 [Category] => 1 [Value] => 60 [Procentage] => 0 )
)
How can I extract a row by SocketDecimal?
For example: I want to extract row where SocketDecimal = 50 and make new an array only with that row.
foreach($array as $entry) {
if($entry['SocketDecimal'] == 50)
$newArr[] = $entry;
}
$newArr will contain the desired "row". Of course you can manipulate the if-statement depending on which "row" (I'd just call it array entry) you want to extract.
It's not the best way for big data! It's easy for deep multiarrays.
$arr = array(
array('socket_id'=>1,'name'=>'test1'),
array('socket_id'=>2,'name'=>'test2'),
array('socket_id'=>3,'name'=>'test3'),
array('socket_id'=>2,'name'=>'test4')
);
$newArr = array();
foreach($arr as $row){
foreach($row as $key=>$r){
if($key == 'socket_id' && $r==2)
$newArr[] = $row;
}
}
print_r($newArr);
$result = array();
foreach($input as $i){
if($i['SocketDecimal']==50)
$result[]=$i;
}
You can do it by this method
foreach ($yourarray as $key => $value){
$newarray = array("SocketDecimal"=>$value["SocketDecimal"];
}
print_r($newarray);
If your result array is like given below
$arr = array(
array( 'SocketID' => 1, 'SocketName' => 'Name', 'SocketDecimal' => 0, 'SocketHex' => 0, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 100, 'Procentage' => 0 ),
array ( 'SocketID' => 2, 'SocketName' => 'Name2', 'SocketDecimal' => 50, 'SocketHex' => 32, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 800, 'Procentage' => 0 ),
array ( 'SocketID' => 3, 'SocketName' => 'Name3', 'SocketDecimal' => 100, 'SocketHex' => 64, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 60, 'Procentage' => 0 )
);
print_r($arr);
Get row for SocketDecimal=50 by following loop:
<pre>
$resultArr = '';
foreach($arr as $recordSet)
{
if($recordSet['SocketDecimal'] == 50)
{
$resultArr[] = $recordSet;
break;
}
}
</pre>
print_r($resultArr);
break foreach loop so that it will not traverse for all the array when SocketDecimal(50) founded.
You can use array_column + array_search combo
$array = Array (
"0" => Array ( "SocketID" => 1, "SocketName" => "Name", "SocketDecimal" => 0, "SocketHex" => 00, "SocketAtt" => 1, "Category" => 1, "Value" => 100, "Procentage" => 0 ) ,
"1" => Array ( "SocketID" => 2, "SocketName" => "Name2", "SocketDecimal" => 50, "SocketHex" => 32, "SocketAtt" => 1, "Category" => 1, "Value" => 800, "Procentage" => 0 ),
"2" => Array ( "SocketID" => 3, "SocketName" => "Name3", "SocketDecimal" => 100, "SocketHex" => 64, "SocketAtt" => 1, "Category" => 1, "Value" => 60 ,"Procentage" => 0 )
);
var_dump($array[array_search(50,array_column($array,'SocketDecimal'))]);

Remove element from array in php

I am new to php and i want to remove element from array Here is my array:
Array
(
[Total] => 21600000
[Items] => Array
(
[2-13] => Array
(
[Item] => 2
[PID] => 13
[UPrice] => 11000000
[Qty] => 1
[Total] => 11000000
)
[58-167] => Array
(
[Item] => 58
[PID] => 167
[UPrice] => 5300000
[Qty] => 1
[Total] => 5300000
)
)
)
And i want to remove array element by PID.
I have try this but no luck:-
$ShoppingBag =$_SESSION['ssss'];
if ($ShoppingBag !== null && $ShoppingBag['Total'] > 0) {
foreach ($ShoppingBag['Items'] as $IOrder) {
if($IOrder["PID"]==13)
{
unset($ShoppingBag[$IOrder]);
}else
{
}
}
}
Please help. Thanks
You can try with one simple array map :)
$arr = [
'Total' => 21600000,
'Items' => [
'2-13' => [
'Item' => 2,
'PID' => 13,
'UPrice' => 11000000,
'Qty' => 1,
'Total' => 11000000
],
'58-167'=> [
'Item' => 58,
'PID' => 167,
'UPrice' => 5300000,
'Qty' => 1,
'Total' => 5300000
]
]
];
$test = array_map(function($ar) {
foreach($ar as $k=>$i) {
if( isset($i['PID']) && $i['PID'] == '13')
unset($ar[$k]);
}
return $ar; } , $arr);
var_dump($test);
You need 2 loop to do the action you want.
foreach($my_array as $key=>$value)
{
if(is_array($value))
{
foreach($value as $k=>$v)
{
if($k == 'PID')
{
unset($value[$k]);
}
}
}
}
with this you can remove only element with key PID.
Hi youre unsetting the $IOrder instead of the Item that you want to delete:
This code is a solution an i tested it :
$ShoppingBag = Array
(
"Total" => 21600000,
"Items" => Array
(
"2-13" => Array
(
"Item" => 2,
"PID" => 13,
"UPrice" => 11000000,
"Qty" => 1,
"Total" => 11000000,
),
"58-167" => Array
(
"Item" => 58,
"PID" => 167,
"UPrice" => 5300000,
"Qty" => 1,
"Total" => 5300000,
),
),
);
foreach($ShoppingBag["Items"] as $key => $value){
if($value["PID"]==13){
unset($ShoppingBag["Items"][$key]);
}
}
You should know that always when you're using foreach loop the foreach( $a as $b ) when you do something to $b , $a remains the same because tey are different variables :)
Hope it will help you .
Regards.
$arr = [
'Total' => 21600000,
'Items' => [
'2-13' => [
'Item' => 2,
'PID' => 13,
'UPrice' => 11000000,
'Qty' => 1,
'Total' => 11000000
],
'58-167'=> [
'Item' => 58,
'PID' => 167,
'UPrice' => 5300000,
'Qty' => 1,
'Total' => 5300000
]
]
];
$pid_to_remove = 13;
$new_ar = array_filter(
$arr,
function ($v) using ($pid_to_remove) {
return (!isset($v['PID'])) || ($v['PID'] != $pid_to_remove);
}
);

Categories