I am php noob. I have searched Google very thoroughly past couple of days and can't figure that out.
I have multidimensional array I have to convert to radio buttons with unique ID and values, but I can't seem to do it.
The json array:
Array
(
[0] => Array
(
[0] => Array
(
[available] => 1
[courier] => 1
[type] => 1
[price] => 42.89
[transitDays] => 3
)
[1] => Array
(
[available] => 1
[courier] => 1
[type] => 3
[price] => 50.50
[transitDays] => 4
)
[2] => Array
(
[available] => 0
)
...
)
[1] => Array
(
[0] => Array
(
[available] => 1
[courier] => 2
[type] => 1
[price] => 111
[transitDays] => 11
)
[1] => Array
(
[available] => 0
[courier] => 2
[type] => 4
[price] => 22
[transitDays] => 22
)
...
)
)
I need to make every output some of the values of every ['available']==1 array into radio buttons and on select be able to retrieve the data after form submission.
<p class="row"><input type="radio" id="option-<?php echo $i ?> value="service-<?php echo $i ?>" name="type" "> <?php echo $service['type']; ?> will cost <?php echo $service['price']; ?> and take <?php echo $service['days']; ?></p>
I have tried flattening arrays and spew available results, but I can't assign unique ID's then.
I tried
foreach ($providers as $provider) {
$mergeProvider = array_merge($provider);
foreach ($provider as $services){
$service = array_merge($services);
if( $service['available'] == 0 ) { unset($service); }
$serviceCount = count($service);
else {
include('offer.php'); //where is input type="button"
}
but this does not allow me unique ID's.
If I do:
foreach ($providers as $provider) {
$mergeProvider = array_merge($provider);
foreach ($provider as $services){
$service = array_merge($services);
$serviceCount = count($services);
for( $i = 1; $i < $serviceCount; $i++ ) {
echo "<pre>";
echo $serviceCount . "</pre>";
it spews out $serviceCount amount of different options where same option has different ID within it.
What can I do?
As an answer to the question in your comment:
You mean how to map the service-10 back to the array?
You then you need a way to get the '10' from the string 'service-10'. But that can go wrong when the numbers become greater than 10. For example 110 (1 and 10).
So I've added another example of how to could do this. I've updated the code with a pipe to separate the $key and the $subkey:
$uniqueKey = $key . '|' . $subKey;
I've also added a var_dump so you can see the mapped data that it matches.
// for example, this is your index.php
<html>
<head></head>
<body>
<form id="theForm" name="theForm" method="POST" action="submit.php">
<?php
$items = array(
0 => array(
0 => array(
"available" => 1,
"courier" => 1,
"type" => 1,
"price" => 42.89,
"transitDays" => 3
),
1 => array(
"available" => 1,
"courier" => 1,
"type" => 3,
"price" => 50.50,
"transitDays" => 4
),
),
1 => array(
0 => array(
"available" => 1,
"courier" => 2,
"type" => 1,
"price" => 111,
"transitDays" => 11
),
1 => array(
"available" => 0,
"courier" => 2,
"type" => 4,
"price" => 22,
"transitDays" => 22
),
)
);
foreach($items as $key => $item) {
foreach($item as $subKey => $subItem) {
if ($subItem["available"] === 1) {
$uniqueKey = $key . '|' . $subKey;
echo sprintf(
'<p class="row"><input type="radio" id="option-%1$s" value="service-%1$s" name="type">%2$s will cost %3$s and take %4$s</p>',
$uniqueKey,
$subItem["type"],
$subItem["price"],
$subItem["transitDays"]
);
}
}
}
?>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
For example this is your submit.php
<?php
$items = array(
0 => array(
0 => array(
"available" => 1,
"courier" => 1,
"type" => 1,
"price" => 42.89,
"transitDays" => 3
),
1 => array(
"available" => 1,
"courier" => 1,
"type" => 3,
"price" => 50.50,
"transitDays" => 4
),
),
1 => array(
0 => array(
"available" => 1,
"courier" => 2,
"type" => 1,
"price" => 111,
"transitDays" => 11
),
1 => array(
"available" => 0,
"courier" => 2,
"type" => 4,
"price" => 22,
"transitDays" => 22
),
)
);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['type'])) {
$type = $_POST['type'];
$positionDash = strpos($type, '-');
$positionPipe = strpos($type, '|');
if (false !== $positionDash && false !== $positionPipe) {
$tail = substr($type, $positionDash+1);
$tree = explode('|', $tail);
$mappedData = $items[$tree[0]][$tree[1]];
var_dump($mappedData);
}
}
}
Maybe you can create a unique key based on the keys of the foreach loops.
Then when you post the form, the name field will contain a unique value like service-00, service-01, service-10
For example:
$items = array(
0 => array(
0 => array(
"available" => 1,
"courier" => 1,
"type" => 1,
"price" => 42.89,
"transitDays" => 3
),
1 => array(
"available" => 1,
"courier" => 1,
"type" => 3,
"price" => 50.50,
"transitDays" => 4
),
),
1 => array(
0 => array(
"available" => 1,
"courier" => 2,
"type" => 1,
"price" => 111,
"transitDays" => 11
),
1 => array(
"available" => 0,
"courier" => 2,
"type" => 4,
"price" => 22,
"transitDays" => 22
),
)
);
// then loop through the $items and create unique key
foreach($items as $key => $item) {
foreach($item as $subKey => $subItem) {
if ($subItem["available"] === 1) {
$uniqueKey = $key . $subKey;
echo sprintf(
'<p class="row"><input type="radio" id="option-%1$s" value="service-%1$s" name="type">%2$s will cost %3$s and take %4$s</p>',
$uniqueKey,
$subItem["type"],
$subItem["price"],
$subItem["transitDays"]
);
}
}
}
Related
Lets say, I have the following array:
$array = array(
array(
"id" => 1,
"name" => "Europe",
"path" => "/"
),
array(
"id" => 2,
"name" => "Germany",
"path" => "/1/"
),
array(
"id" => 3,
"name" => "France",
"path" => "/1/"
),
array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
)
);
As you can see, its a multidimensional array with 3 properites in earch 2nd level array: id, name and path. The path is a path structure based on the parent-id of its parent. For example, Germany (id=2) has belongs to Europe, so the path is "/1/" (ID 1 = Europe) and Berlin in Germany has the path "/1/2/" which means "/Europe/Germany/"
Now, I am trying to create a tree-array out of this, which should somehow look like:
$result = array(
1 => array(
"id" => 1,
"name" => "Europe",
"path" => "/",
"childs" => array(
2 => array(
"id" => 2,
"name" => "Germany",
"path" => "/1/",
"childs" => array(
4 => array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
5 => array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
)
)
),
3 => array(
"id" => 3,
"name" => "France",
"path" => "/1/"
)
)
)
);
I have already tried to create a function with internal references, but this didn't works for me:
public static function pathToTree($items) {
$array = array();
$result = array();
foreach($items AS $res) {
$ids = explode("/", ltrim($res["path"] . $res["id"], "/"));
$count = count($ids);
$tmp = &$result;
foreach( $ids AS $id) {
if($count == 1) {
$tmp = $res;
$tmp["childs"] = array();
$tmp = &$tmp["childs"];
}
else {
$tmp[$id] = array(
"childs" => array()
);
$tmp = &$tmp[$id]["childs"];
}
$count--;
}
}
return $array;
}
Ok, I think I just found a solution:
function pathToTree($array){
$tree = array();
foreach($array AS $item) {
$pathIds = explode("/", ltrim($item["path"], "/") . $item["id"]);
$current = &$tree;
foreach($pathIds AS $id) {
if(!isset($current["childs"][$id])) $current["childs"][$id] = array();
$current = &$current["childs"][$id];
if($id == $item["id"]) {
$current = $item;
}
}
}
return $tree["childs"];
}
This is a dynamice solution for 1-n depth. Look at my example at http://ideone.com/gn0XLp . Here I tested it with some level:
Continent
Country
City
City-District
City-Subdistrict
City Sub-Sub-District
I've created a recursive function:
// The array
$array = array(
array(
"id" => 1,
"name" => "Europe",
"path" => "/"
),
array(
"id" => 2,
"name" => "Germany",
"path" => "/1/"
),
array(
"id" => 3,
"name" => "France",
"path" => "/1/"
),
array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
),
array(
"id" => 6,
"name" => "Asia",
"path" => "/"
),
array(
"id" => 7,
"name" => "India",
"path" => "/6/"
),
array(
"id" => 7,
"name" => "Mumbai",
"path" => "/6/7"
),
array(
"id" => 8,
"name" => "Delhi",
"path" => "/6/7"
),
);
// The recursive function
function createTree($input, &$result = array(), $key = null) {
if ($key == "id") {
$result["temp"]["id"] = $input;
}
if ($key == "name") {
$result["temp"]["name"] = $input;
}
if ($key == "path") {
$result["temp"]["path"] = $input;
$levels = is_string($input) ? array_values(array_filter(explode('/', $input))) : null;
if ($input == "/") {
$result[$result["temp"]["id"]] = $result["temp"];
}
if (count($levels) == 1) {
$result[$levels[0]]["childs"][$result["temp"]["id"]] = $result["temp"];
}
if (count($levels) == 2) {
$result[$levels[0]]["childs"][$levels[1]]["childs"][$result["temp"]["id"]] = $result["temp"];
}
unset($result["temp"]);
}
if (is_array($input)) {
foreach($input as $key => $value) {
createTree($value, $result, $key);
}
}
return $result;
}
// The result
array (
1 =>
array (
'id' => 1,
'name' => 'Europe',
'path' => '/',
'childs' =>
array (
2 =>
array (
'id' => 2,
'name' => 'Germany',
'path' => '/1/',
'childs' =>
array (
4 =>
array (
'id' => 4,
'name' => 'Berlin',
'path' => '/1/2/',
),
5 =>
array (
'id' => 5,
'name' => 'Munich',
'path' => '/1/2/',
),
),
),
3 =>
array (
'id' => 3,
'name' => 'France',
'path' => '/1/',
),
),
),
6 =>
array (
'id' => 6,
'name' => 'Asia',
'path' => '/',
'childs' =>
array (
7 =>
array (
'id' => 7,
'name' => 'India',
'path' => '/6/',
'childs' =>
array (
7 =>
array (
'id' => 7,
'name' => 'Mumbai',
'path' => '/6/7',
),
8 =>
array (
'id' => 8,
'name' => 'Delhi',
'path' => '/6/7',
),
),
),
),
),
)
As I said in the comment, you need at least three loops to achieve your goals. Here's the function:
function pathToTree($array){
$tree = Array();
for($i=0; $i < count($array); $i++){
if(substr_count($array[$i]["path"], '/') == 1)
$tree[$array[$i]["id"]] = $array[$i];
}
for($i=0; $i < count($array); $i++){
if(substr_count($array[$i]["path"], '/') == 2){
$num = (int)str_replace("/","",$array[$i]["path"]);
$tree[$num]["childs"][$array[$i]["id"]] = $array[$i];
}
}
for($i=0; $i < count($array); $i++){
if(substr_count($array[$i]["path"], '/') == 3){
$num = explode("/", $array[$i]["path"]);
$tree[$num[1]]["childs"][$num[2]]["childs"][$array[$i]["id"]] = $array[$i];
}
}
return $tree;
}
Example:
Consider this array:
$array = array(
array(
"id" => 1,
"name" => "Europe",
"path" => "/"
),
array(
"id" => 2,
"name" => "Germany",
"path" => "/1/"
),
array(
"id" => 3,
"name" => "France",
"path" => "/1/"
),
array(
"id" => 4,
"name" => "Berlin",
"path" => "/1/2/"
),
array(
"id" => 5,
"name" => "Munich",
"path" => "/1/2/"
),
array(
"id" => 6,
"name" => "Asia",
"path" => "/"
),
array(
"id" => 7,
"name" => "China",
"path" => "/6/"
),
array(
"id" => 8,
"name" => "Bangladesh",
"path" => "/6/"
),
array(
"id" => 9,
"name" => "Beijing",
"path" => "/6/7/"
),
array(
"id" => 10,
"name" => "Dhaka",
"path" => "/6/8/"
)
);
if I ran this code:
print_r(pathToTree($array));
the output will be:
Array
(
[1] => Array
(
[id] => 1
[name] => Europe
[path] => /
[childs] => Array
(
[2] => Array
(
[id] => 2
[name] => Germany
[path] => /1/
[childs] => Array
(
[4] => Array
(
[id] => 4
[name] => Berlin
[path] => /1/2/
)
[5] => Array
(
[id] => 5
[name] => Munich
[path] => /1/2/
)
)
)
[3] => Array
(
[id] => 3
[name] => France
[path] => /1/
)
)
)
[6] => Array
(
[id] => 6
[name] => Asia
[path] => /
[childs] => Array
(
[7] => Array
(
[id] => 7
[name] => China
[path] => /6/
[childs] => Array
(
[9] => Array
(
[id] => 9
[name] => Beijing
[path] => /6/7/
)
)
)
[8] => Array
(
[id] => 8
[name] => Bangladesh
[path] => /6/
[childs] => Array
(
[10] => Array
(
[id] => 10
[name] => Dhaka
[path] => /6/8/
)
)
)
)
)
)
Here's the phpfiddle link in case you might try it yourself.
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'))]);
Example my array
Array (
[0] => Array
(
[product_name] => T-Shirt
[product_id] => 231
[user_id] => 22977
)
[1] => Array
(
[product_name] => Shirt
[product_id] => 220
[user_id] => 22977
)
[2] => Array
(
[product_name] => T-Shirt
[product_id] => 226
[user_id] => 16916
)
[3] => Array
(
[product_name] => Bags
[product_id] => 230
[user_id] => 16916
)
[4] => Array
(
[product_name] => Hats
[product_id] => 233
[user_id] => 22977
)
)
How to generate this array to be
User-Id: 22977
1/ Hats
2/ Shirt
3/ T-Shirt
User-Id: 16916
1/ Bags
2/ T-Shirt
$a = array();
$a[] = array("product_name" => "T-Shirt", "product_id" => 231, "user_id" => 22977);
$a[] = array("product_name" => "Shirt", "product_id" => 220, "user_id" => 22977);
$a[] = array("product_name" => "T-Shirt", "product_id" => 226, "user_id" => 16916);
$a[] = array("product_name" => "Bags", "product_id" => 230, "user_id" => 16916);
$a[] = array("product_name" => "Hats", "product_id" => 233, "user_id" => 22977);
$return = array();
foreach ($a as $key => $value) {
$return[$value["user_id"]][] = $value["product_name"];
}
foreach ($return as $key => $value) {
echo "User-Id: " . $key . "\r\n";
$i = 0;
foreach ($value as $val) {
echo ++$i . "/ " . $val . "\r\n";
}
}
Output will be:
User-Id: 22977
1/ T-Shirt
2/ Shirt
3/ Hats
User-Id: 16916
1/ T-Shirt
2/ Bags
You can use this:
$testarray = array(
array(
"product_name" => 'T-Shirt',
"product_id" => 231,
"user_id" => 22977),
array
(
"product_name" => 'Shirt',
"product_id" => 220,
"user_id" => 22977,
),
array
(
"product_name" => 'T-Shirt',
"product_id" => 226,
"user_id" => 16916,
),
array
(
"product_name" => 'Bags',
"product_id" => 230,
"user_id" => 16916,
),
array
(
"product_name" => 'Hats',
"product_id" => 233,
"user_id" => 22977,
),
);
$newArray = array();
foreach ($testarray as $subArray) {
$newArray[$subArray["user_id"]][] = $subArray['product_name'];
}
var_dump ($newArray);
Output is:
array
22977 =>
array
0 => string 'T-Shirt' (length=7)
1 => string 'Shirt' (length=5)
2 => string 'Hats' (length=4)
16916 =>
array
0 => string 'T-Shirt' (length=7)
1 => string 'Bags' (length=4)
<?php
//initialize array
$array = Array(
'0' => Array
(
'product_name' => 'T-Shirt',
'product_id' => 231,
'user_id' => 22977
),
'1' => Array
(
'product_name' => 'Shirt',
'product_id' => 220,
'user_id' => 22977
),
'2' => Array
(
'product_name' => 'T-Shirt',
'product_id' => 226,
'user_id' => 16916
),
'3' => Array
(
'product_name' => 'Bags',
'product_id' => 230,
'user_id' => 16916
),
'4' => Array
(
'product_name' => 'Hats',
'product_id' => 233,
'user_id' => 22977
)
);
//result will be here
$result = array();
foreach ($array as $key => $value) {
//check if we have keys group or names to avoid errors
if(!isset($value['user_id']) || !isset($value['product_name']))
continue;
//make a key in result array if its not exist
if(!isset($result[$value['user_id']]))
{
$result[$value['user_id']] = array($value['product_name']);
}
else
{
//add a values to key if it exists
$result[$value['user_id']][] = $value['product_name'];
//filter same values
$result[$value['user_id']] = array_values(array_unique($result[$value['user_id']]));
}
}
echo '<pre>';
print_r($result);
echo '</pre>';
?>
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);
}
);
$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?