I have this hook:
<?php
use Illuminate\Database\Capsule\Manager as Capsule;
function hook_productPrice($vars){
$ProductsPriceArray = Capsule::table("tblpricing")->where("type", "=", "product")->get();
$productPrice = json_decode(json_encode($ProductsPriceArray), true);
return array("productPrice" => $productPrice);
}
add_hook("ClientAreaPage", 1, "hook_productPrice");
When i run it, i get this smarty array:
$productPrice
Origin: "Smarty object"
Value
Array (1)
0 => Array (16)
id => "2"
type => "product"
currency => "1"
relid => "1"
msetupfee => "0.00"
qsetupfee => "0.00"
ssetupfee => "0.00"
asetupfee => "0.00"
bsetupfee => "0.00"
tsetupfee => "0.00"
monthly => "10.00"
quarterly => "20.00"
semiannually => "30.00"
annually => "40.00"
biennially => "-1.00"
triennially => "-1.00"
As you can see the id of the array is 0. How can I get the id of the table that has the same key of the array?
I want to use the variable to show up the price like this:
$productPrice[2]['monthly']
You need to create new associative array that uses the id
field as the key.
<?php
use Illuminate\Database\Capsule\Manager as Capsule;
function hook_productPrice($vars)
{
$ProductsPriceArray = Capsule::table("tblpricing")->where("type", "=", "product")->get();
$rows = json_decode(json_encode($ProductsPriceArray), true);
$productPrice = [];
foreach($rows as $currRow)
{
$output[$currRow['id']] = $currRow;
}
return array("productPrice" => $productPrice);
}
add_hook("ClientAreaPage", 1, "hook_productPrice");
This is such a common pattern, you might as well create a function for it and stick it somewhere.
<?php
$productPrice = [
['id' => 10, 'type' => 'product', 'monthly' => '10.00'],
['id' => 11, 'type' => 'product', 'monthly' => '11.00'],
['id' => 12, 'type' => 'subscription', 'monthly' => '12.00'],
['id' => 13, 'type' => 'service', 'monthly' => '13.00'],
['id' => 14, 'type' => 'service', 'monthly' => '14.00']
];
function array_map_by_field($array, $keyField, $valueField=null)
{
$output = [];
foreach($array as $currRow)
{
if(array_key_exists($keyField, $currRow))
{
if(!empty($valueField))
{
$output[$currRow[$keyField]] = $currRow[$valueField];
}
else
{
$output[$currRow[$keyField]] = $currRow;
}
}
}
return $output;
}
$output = array_map_by_field($productPrice, 'id');
print_r($output);
$output = array_map_by_field($productPrice, 'id', 'monthly');
print_r($output);