Перехват WHMCS для извлечения таблицы в массив

#mysql #hook #smarty #whmcs

#mysql #перехват #умный #whmcs

Вопрос:

У меня есть этот перехват:

 <?php  

use IlluminateDatabaseCapsuleManager 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"
  

Как вы можете видеть, идентификатор массива равен 0.
Как я могу получить идентификатор таблицы, которая имеет тот же ключ массива?

Я хочу использовать переменную для отображения цены следующим образом: $productPrice[2]['monthly']

Ответ №1:

Вам нужно создать новый ассоциативный массив, который использует id поле в качестве ключа.

 <?php
use IlluminateDatabaseCapsuleManager 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);