gpt4 book ai didi

php - 处理对未定义索引和 E_NOTICE 的赋值

转载 作者:行者123 更新时间:2023-12-03 09:06:36 25 4
gpt4 key购买 nike

Looks like a lot of people did not understand the question, the notice I am getting is not about $fromdatabase, it's about $data[$key]



因为我可以在开发环境中看到我得到的 $fromDatabase[$key],错误消息是针对以下行的:$data [$key] = $this->getSomeValue ($value);

Even if I do $data ['mykey'] I get the message undefined index mykey



我有一种情况,我需要为关联数组的未定义索引分配一些值。像这样的东西:
$data = array (  );

foreach ( $something as $key => $value)
{
/** If I do this then there is no notice **/
$data['body'][$key] = NULL;

foreach ( $fromDatabase as $xyz)
{
$data['body'][$key] = $this->getSomeValue ($xyz);
}
}
$fromDatabase未知和 $key无法事先预测,都是动态的。

在这种情况下如何处理 E_NOTICE(未定义索引)?

E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.



PHP 手册说明了这一点,但是为什么在将元素附加到未初始化的数组时出现错误?

最佳答案

您只需要确保 $fromDatabase存在并且是一个数组,其余的就可以了。
$data[$key]如果它不存在和 $key 将被创建和 $value会自动设置。

$data = array (  );

if (isset($fromDatabase) && is_array($fromDatabase))
foreach ( $fromDatabase as $key => $value )
{
$data[$key] = $this->getSomeValue ($value); // You made a typo "key" => "$key"
}

编辑:我无法重现您的错误
$fromDatabase = ['test' => 1, 42 => 'some strange value'];

$data = array ( );
foreach ( $fromDatabase as $key => $value )
{
$data[$key] = $value;
}

print_r($data);

输出(对我而言):
Array
(
[test] => 1
[42] => some strange value
)

重新编辑:
$data = array (  );

将其更改为
$data = array('body' => array());

关于php - 处理对未定义索引和 E_NOTICE 的赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33548416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com