php - how to sum values of the multidimensional array - php

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% :)

Related

Convert an input array into a Google chart JS?

I am trying to convert an input to an array which i need to us to display a Google Chart
The input array I got looks like,
$inputArray = [
['date' => '2016-12-10', 'code' => 'P'],
['date' => '2016-12-15', 'code' => 'P'],
['date' => '2017-02-10', 'code' => 'P'],
['date' => '2017-02-14', 'code' => 'P'],
['date' => '2017-03-10', 'code' => 'P'],
['date' => '2017-03-05', 'code' => 'U'],
['date' => '2017-03-11', 'code' => 'U'],
['date' => '2017-03-12', 'code' => 'P'],
['date' => '2017-04-07', 'code' => 'T'],
['date' => '2017-04-18', 'code' => 'P'],
['date' => '2017-04-19', 'code' => 'T'],
['date' => '2017-07-10', 'code' => 'P'],
];
Now I need to group by year and month and sum the code value (4 different values). For these I use a loop like so
function readPerMonth($tmpArray) {
if (empty($tmpArray)) {
$output[$year][$month] = ['P' => 0, 'T' => 0, 'U' => 0, 'E' => 0];
} else {
$output = [];
foreach ($tmpArray as $value) {
$year = date('Y', strtotime($value['date']));
$month = date('M', strtotime($value['date']));
if (empty($output[$year][$month]))
$output[$year][$month] = ['P' => 0, 'T' => 0, 'U' => 0, 'E' => 0];
// Check for incident intensity
$output[$year][$month][$value['code']] += 1;
}
}
ksort($output);
ksort($output[$year][$month]);
return $output;
}
and this gives me the Following output, hence last array is in another order???
Array
(
[2017] => Array
(
[Feb] => Array
(
[P] => 11
[T] => 0
[U] => 0
[E] => 0
)
[Mar] => Array
(
[P] => 20
[T] => 0
[U] => 0
[E] => 0
)
[Apr] => Array
(
[P] => 12
[T] => 0
[U] => 0
[E] => 0
)
[May] => Array
(
[P] => 21
[T] => 0
[U] => 0
[E] => 0
)
[Jun] => Array
(
[E] => 0
[P] => 7
[T] => 0
[U] => 1
)
)
)
and I this is an input Array which i need to convert in this JS to plot a stacked Google chart
$output = [
['2016-dec', 2, 0, 0, 0,'2'],
['2017-feb', 2, 0, 0, 0, '2'],
['2017-mar', 2, 0, 2, 0,'4'],
['2017-apr', 1, 1, 0, 0,'2'],
['2017-may', 1, 0, 0, 0, '1'],
];
My php function looks like this
function phpToJS($inputPHP) {
$return = '';
foreach ($inputPHP as $year => $months) {
foreach ($months as $monthValue => $codeValues) {
$sum = 0;
$return .= "['" . $year . " - " . $monthValue . "', ";
foreach ($codeValues as $key => $code) {
if ($key == '') {
$return .= $code;
} else {
$return .= $code . ',';
}
$sum += $code;
}
$return .= ",'" . $sum . "'],";
}
}
return $return;
}
$tmpArr = readPerMonth($inputArray);
$output = phpToJS($tmpArr);
but because of the last Array which isn't in the right order the Google Chart displays wrong.
ps: so sorry to have hit send and not finishing my question title :/

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

how to display multidimensional array without knowing depth?

I have one large multidimensional array(I dnt the depth of array) and I want to display it in tabular form . this is one array from my array
[Kai Roger Tester] => Array
(
[Ikke navngitt] => Array
(
[status] => Array
(
[documents_green] => 0
[documents_yellow] => 0
[documents_red] => 3
[waiting_approval_documents] => 1
[waiting_verfication_documents] => 0
[under_construction_documents] => 3
)
)
[Finnfjord] => Array
(
[NVD test] => Array
(
[status] => Array
(
[documents_green] => 0
[documents_yellow] => 0
[documents_red] => 1
[waiting_approval_documents] => 0
[waiting_verfication_documents] => 0
[under_construction_documents] => 5
)
)
[status] => Array
(
[documents_green] => 0
[documents_yellow] => 0
[documents_red] => 0
[waiting_approval_documents] => 0
[waiting_verfication_documents] => 0
[under_construction_documents] => 2
)
)
[Endringslogg] => Array
(
[status] => Array
(
[documents_green] => 0
[documents_yellow] => 0
[documents_red] => 0
[waiting_approval_documents] => 0
[waiting_verfication_documents] => 0
[under_construction_documents] => 1
)
)
[Laste opp doc] => Array
(
[status] => Array
(
[documents_green] => 0
[documents_yellow] => 0
[documents_red] => 1
[waiting_approval_documents] => 0
[waiting_verfication_documents] => 0
[under_construction_documents] => 1
)
)
[status] => Array
(
[documents_green] => 1
[documents_yellow] => 0
[documents_red] => 6
[waiting_approval_documents] => 3
[waiting_verfication_documents] => 4
[under_construction_documents] => 13
)
)
[Prosess 1] => Array
(
[AF Decom] => Array
(
[status] => Array
(
[documents_green] => 1
[documents_yellow] => 0
[documents_red] => 0
[waiting_approval_documents] => 0
[waiting_verfication_documents] => 0
[under_construction_documents] => 3
)
)
[status] => Array
(
[documents_green] => 7
[documents_yellow] => 0
[documents_red] => 2
[waiting_approval_documents] => 0
[waiting_verfication_documents] => 0
[under_construction_documents] => 11
)
)
Folder Name green yellow red
Kai Roger Tester 1 0 6
Ikke navngitt' 0 0 3
Finnfjord 0 0 0
NVD test 0 0 1
Process1 1 1 0
I tired with below method
public static function getfoldertable($array, $prefix = '') {
$body_start = "<tbody>";
if (count($array) > 0 && is_array($array)) {
$i = 0;
foreach ($array as $key => $row) {
$body_start.='<tr>
<td>'.$i.'</td>
<td>'.$key.'</td>
<td>'.$row['status']['documents_green'].'</td>
<td>'.$row['status']['documents_yellow'].'</td>
<td>'.$row['status']['documents_red'].'</td>
</tr>';
$body_start.= self::getfoldertable($row, $prefix . '-');
$i++;
}
$body_start.="</tbody>";
}
//echo $body_start; die;
return $body_start;
}
Can anyone help me how can i display this?
Thanks in advance
Here is a function you could use for generating that output:
function getTreeHTML($tree, $level = 0) {
$html = "";
$indent = str_repeat(" ", $level * 2);
foreach ($tree as $key => $value) {
if ($key == "status") continue;
$html .= "
<tr><td>$indent$key</td>
<td>{$value['status']['documents_green']}</td>
<td>{$value['status']['documents_yellow']}</td>
<td>{$value['status']['documents_red']}</td>
</tr>" . getTreeHTML($value, $level+1);
}
return $html;
}
If the input data is defined like this:
$input = array (
'Kai Roger Tester' =>
array (
'Ikke navngitt' =>
array (
'status' =>
array (
'documents_green' => 0,
'documents_yellow' => 0,
'documents_red' => 3,
'waiting_approval_documents' => 1,
'waiting_verfication_documents' => 0,
'under_construction_documents' => 3,
),
),
'Finnfjord' =>
array (
'NVD test' =>
array (
'status' =>
array (
'documents_green' => 0,
'documents_yellow' => 0,
'documents_red' => 1,
'waiting_approval_documents' => 0,
'waiting_verfication_documents' => 0,
'under_construction_documents' => 5,
),
),
'status' =>
array (
'documents_green' => 0,
'documents_yellow' => 0,
'documents_red' => 0,
'waiting_approval_documents' => 0,
'waiting_verfication_documents' => 0,
'under_construction_documents' => 2,
),
),
'Endringslogg' =>
array (
'status' =>
array (
'documents_green' => 0,
'documents_yellow' => 0,
'documents_red' => 0,
'waiting_approval_documents' => 0,
'waiting_verfication_documents' => 0,
'under_construction_documents' => 1,
),
),
'Laste opp doc' =>
array (
'status' =>
array (
'documents_green' => 0,
'documents_yellow' => 0,
'documents_red' => 1,
'waiting_approval_documents' => 0,
'waiting_verfication_documents' => 0,
'under_construction_documents' => 1,
),
),
'status' =>
array (
'documents_green' => 1,
'documents_yellow' => 0,
'documents_red' => 6,
'waiting_approval_documents' => 3,
'waiting_verfication_documents' => 4,
'under_construction_documents' => 13,
),
),
'Prosess 1' =>
array (
'AF Decom' =>
array (
'status' =>
array (
'documents_green' => 1,
'documents_yellow' => 0,
'documents_red' => 0,
'waiting_approval_documents' => 0,
'waiting_verfication_documents' => 0,
'under_construction_documents' => 3,
),
),
'status' =>
array (
'documents_green' => 7,
'documents_yellow' => 0,
'documents_red' => 2,
'waiting_approval_documents' => 0,
'waiting_verfication_documents' => 0,
'under_construction_documents' => 11,
),
),
);
...and you would call that function like this:
$html = getTreeHTML($input);
...embedding that HTML result as follows in a table:
<table border=1>
<tr><th>Folder Name</th><th>green</th><th>yellow</th><th>red</th></tr>
<?=$html?>
</table>
...then the output would look in a browser like this:
Use RecursiveIterator.
Working code:
$array = array();
$array[0] = array('test' => array('asdf', 'asdf', array('asf', array('asdfads', 'asdf' => array(234,234,234)))));
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $key => $item) {
if (is_array($item)) {
echo '<pre>';print_r($item);echo '</pre>';
}
}

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

Join 2 multidimensional array

$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?

Categories