WHMCS Hook 将 table 检索到数组中

WHMCS Hook to retrieve table into an array

我有这个钩子:

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

当我 运行 它时,我得到了这个聪明的数组:

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

可以看到数组的id是0。 如何获取具有相同数组键的 table 的 ID?

我想像这样使用变量来显示价格: $productPrice[2]['monthly']

您需要创建使用 id 字段作为键的新关联数组。

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

这是一个很常见的模式,你不妨为它创建一个函数并将它贴在某个地方。

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