利用保存在TXT文件(PHP)中的数组数据

问题描述 投票:-1回答:3

我正在尝试通过表单提交来使用保存到list.txt的数据,并在页面上随机显示。

index.php

<?php
    //$list = file_get_contents('list.txt'); //Tested without fopen

    $myfile = fopen('list.txt', "r") or die ("");

    $list = fread($myfile,filesize('list.txt'));

    $bg0 = array($list ,'yellow'); // array of colors

    fclose($myfile);

    $i = rand(0, count($bg0)-1); // generate random number size of the array
    $selectedColor = "$bg0[$i]"; // set variable equal to which random color was chosen

    echo selectedColor;
?>

list.txt

'red', 'blue', 'green'
php arrays text fopen file-get-contents
3个回答
1
投票

我不确定您要在这里实现什么,但是您遇到的问题很少:

1)selectedColor

应为$ selectedColor

2)加载“数组”。

您不能简单地加载文本并期望php猜测格式。如果要加载文件并将其视为数组,则需要指示php进行加载。

在您的示例中,您可以例如拆分文本并修剪不需要的字符:

  $list = explode(',', $list);
  array_walk($list, function(&$elem) {
    $elem = trim($elem, ' \'');
  });

3)$ selectedColor = $ bg0 [$ i];

替换:

$selectedColor = "$bg0[$i]";

with:

$selectedColor = $bg0[$i];

4)数组推送

此行不正确:

$bg0 = array($list ,'yellow'); // array of colors

替换为:

$bg0 = array_merge($list, ['yellow']); // array of colors

如果要对单个数组进行操作,可以使用array_push,但请确保稍后更改要使用的变量。]​​>

例如:

<?php

  //$list = file_get_contents('list.txt'); //Tested without fopen

  $myfile = fopen('list.txt', "r") or die ("");

  $list = fread($myfile,filesize('list.txt'));

  $list = explode(',', $list);
  array_walk($list, function(&$elem) {
    $elem = trim($elem, ' \'');
  });

  $bg0 = array_merge($list , ['yellow']); // array of colors

  fclose($myfile);

  $i = rand(0, count($bg0)-1); // generate random number size of the array
  $selectedColor = $bg0[$i]; // set variable equal to which random color was chosen

  echo $selectedColor;
  ?>

0
投票

您需要使用explode()将字符串转换为数组,然后根据需要添加其他元素:


0
投票
  • 您需要分割输入值。这可以通过正则表达式简单地完成。
© www.soinside.com 2019 - 2024. All rights reserved.