在数组键中分配变量
Assign variable in array key
我正在开发 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'],
不工作
尝试像这样连接:
$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'],
);
Notes:
- As already Nick pointed out, including count into a key name doesn't make much sense, but I guess you just wanted to provide a sample ;-)
- The double-quote in PHP is specially helpful for concatenating, but the single-quote should be used to improve performance (PHP does not search or handle dollar-signs in single quotes).
你可以对数组键使用双引号,然后使用 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'],
];
$number = 3;
$array1 = array("test$number" => "Sample");
$array2 = array("test".$number => "Sample");
print_r($array1); //Array ( [test3] => Sample )
print_r($array2); //Array ( [test3] => Sample )
你应该学习PHP基础。
我正在开发 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'],
不工作
尝试像这样连接:
$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'],
);
Notes:
- As already Nick pointed out, including count into a key name doesn't make much sense, but I guess you just wanted to provide a sample ;-)
- The double-quote in PHP is specially helpful for concatenating, but the single-quote should be used to improve performance (PHP does not search or handle dollar-signs in single quotes).
你可以对数组键使用双引号,然后使用 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'],
];
$number = 3;
$array1 = array("test$number" => "Sample");
$array2 = array("test".$number => "Sample");
print_r($array1); //Array ( [test3] => Sample )
print_r($array2); //Array ( [test3] => Sample )
你应该学习PHP基础。