警告:key()期望参数1为数组,给定字符串

时间:2018-07-07 17:19:27

标签: php

我有一个关联数组,只想获取第一个键,但是我收到警告。参见下面的示例:

<?php
// Warning=> array_keys() expects parameter 1 to be array, string given

$product = array("Test" => array(price=>"9999.00", priceOld=>"", percentageSaved=>0, currency=>"$"));

$keys = key($product);

echo $keys;

我收到以下警告:

Warning: key() expects parameter 1 to be array, string given in C:\Users\admin\Desktop\product.php on line xxx

我为什么会收到此警告的任何建议?

感谢您的答复!

2 个答案:

答案 0 :(得分:1)

我认为您粘贴在问题上的数组不是属性格式的。我可以在您的关联数组键(不带引号的字符串)上看到一些问题。在string键上添加引号后,对我来说效果很好。

<?php
$product = array("Test" => array("price"=>"9999.00", "priceOld"=>"", "percentageSaved"=>0, "currency"=>"$"));
print '<pre>';
print_r($product);
print '</pre>';
$keys = key($product);
echo "Your key is: $keys";
?>

程序输出:

Array
(
    [Test] => Array
        (
            [price] => 9999.00
            [priceOld] => 
            [percentageSaved] => 0
            [currency] => $
        )

)

Your key is: Test

编辑::如果要获取 Test 的内部密钥,请使用类似的array_keys()方法。

 print_r(array_keys($product['Test']));

答案 1 :(得分:-1)

请转到并更改您的php版本。将其更改为v5.6.31,对我有用。