在数组键中分配变量

问题描述 投票:0回答:3

我正在使用prestashop模块,它将使用cURL将其他数据发送到Google Analytics(分析)。而且我对如何将迭代计数变量分配给数组键感到困惑。

例如:

'prXnm' => $order_detail['product_name'],
    'prXid' => $order_detail['product_id'],
    'prXpr' => $order_detail['product_price'],

其中X是一个数字,应该做类似count($order_detail['product_name']);

如何将X实现为数组?因为'prcount($order_detail['product_name'])nm' => $order_detail['product_name'],无效

php arrays prestashop
3个回答
1
投票

尝试串联:

$x = count($order_detail['product_name']);
$result = array(
  "pr${x}nm" => $order_detail['product_name'],
  "pr${x}id" => $order_detail['product_id'],
  "pr${x}pr" => $order_detail['product_price'],
);

注意:

  1. 正如Nick所指出的,将键名包括在内并没有多大意义,但我想您只是想提供一个示例;-)
  2. PHP中的双引号对连接特别有用,但是应使用单引号来提高性能(PHP不会搜索或处理单引号中的美元符号)。

0
投票

您可以对数组键使用双引号,然后使用curly braces syntax注入变量>

<?php

$i = count($order_detail['product_name']);

$arr = [
    "pr${i}nm" => $order_detail['product_name'],
    "pr${i}id" => $order_detail['product_id'],
    "pr${i}pr" => $order_detail['product_price'],
];

0
投票
$number = 3;
$array1 = array("test$number" => "Sample");
$array2 = array("test".$number => "Sample");

print_r($array1); //Array ( [test3] => Sample )
print_r($array2); //Array ( [test3] => Sample )
© www.soinside.com 2019 - 2024. All rights reserved.