【问题标题】:Using a variable as array-key while filling the array在填充数组时使用变量作为数组键
【发布时间】:2017-01-24 10:57:52
【问题描述】:

我想用数据库表中的数据填充一个数组。现在我必须在这个表中列,第一个是id_name,第二个是text。该表目前有 10 行,但也可以有更多。

现在我希望数组采用以下形式:
[value of col "id_name"] => [value of col "text"]

我尝试了以下方法:

while($row_get_text = mysqli_fetch_assoc($res_get_text)) {
    $text = array(
        $row_get_text['id_name'] => $row_get_text['text'],
    );
}

这是第一次,我尝试回显属于home_filter_settings_headline索引的值:

<div id="s_f"><?php echo $text['home_filter_settings_headline']; ?></div>

但不幸的是,这不起作用。可以做我想做的吗?如果是这样,正确的方法是什么?

【问题讨论】:

    标签: php arrays variables


    【解决方案1】:

    尝试:

    $result = []
    while($row_get_text = mysqli_fetch_assoc($res_get_text)) {
        $result[$row_get_text['id_name']] = $row_get_text['text']
    }
    

    【讨论】:

    • 这带来了:Notice: Undefined index: home_filter_settings_headline in [...]
    • 成功了,只有一个; 丢失了。非常感谢! :)
    【解决方案2】:

    您的代码非常正确,但是请尝试进行这些更改 根据您的需要选择text1 tor text2。我不确定哪一个是您的要求。

    $text1 = array();
    $text2 = array();
    while($row_get_text = mysqli_fetch_assoc($res_get_text)) {
        $text1[] = array(
            $row_get_text['id_name'] => $row_get_text['text']
        );
        $text2[$row_get_text['id_name']] = $row_get_text['text'];
    }
    

    【讨论】:

    • 感谢您的回答。带有“text1”的解决方案带来:Notice: Undefined index: home_filter_settings_headline in [...] 在该行中,我想在其中回显索引home_filter_settings_headline 的值。带有“text2”的解决方案带来:Notice: Undefined index: skill (platzhalter) in [...]skill (platzhalter) 是数据库表中 col text 的值,数据库表的每一行都会出现这种情况。
    • 我已经测试过了。有用。至于错误,看来您使用的索引不正确。
    【解决方案3】:

    尝试将它们插入到专门用于文本字段的双引号中,

    while($row_get_text = mysqli_fetch_assoc($res_get_text)) {
        $id_name = $row_get_text['id_name'];
        $text_f = $row_get_text['text'];
        $text = array(
            "$id_name" => "$text_f",
        );
    }
    

    【讨论】:

    • 这带来了:Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in [...]
    • 试过了,这个带来:Notice: Undefined index: home_filter_settings_headline in [...]
    • 你确定这两个值都正确回显我的意思是它们存在。
    • 是的,如果我在 while 中插入 echo $row_get_text_by_lang['id_name'];echo $row_get_text_by_lang['text_de'];,它会回显这两个值。
    【解决方案4】:

    试试这个:

    while($row_get_text = mysqli_fetch_assoc($res_get_text)) {
        $text[$row_get_text['id_name']] = $row_get_text['text'];
    }
    

    【讨论】:

    • 这带来了:Notice: Undefined variable: text in [...]
    • 试过了,带来:Parse error: syntax error, unexpected '=&gt;' (T_DOUBLE_ARROW) in [...]
    • 抱歉错误,请查看更新后的答案
    • 现在它和 Hedin 的回答一样有效。也非常感谢! :)
    • 听起来不错:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2012-08-17
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多