将数据添加到PHP数组值

时间:2016-04-01 02:02:45

标签: php arrays

我想知道以下是否可能,因为谷歌搜索没有得到答案。

我们说我有以下数组:

$data[] = array();
$data[] = "value 1";
$data[] = "value 2";

在每个值的开头,我需要添加this is,这在每个值中都是一致的。

我怎么能做到这一点?

我试过了:

$addData = "this is ";
$data[] = array();
$data[] = $addData . "value 1";
$data[] = $addData . "value 2";

我希望得到这样的解决方案的原因是因为$addData的值可能会改变,但实际值将保持不变。

例如,我有以下代码:

 $directory = "admin/";
 $redirect[] = array();
 $redirect[] = "page1.php";
 $redirect[] = "page2.php";
 $redirect[] = "index.php";
 if(in_array($directory . basename($_SERVER["SCRIPT_FILENAME"]), $redirect)) {
  header("Location: http://example.com/index.php");
}

我需要为每个值添加admin,但如果我的数组列表增长则动态地这样,那么我不需要编辑10个以上的数组值。

最终,如果需要,我只想更改$directory值。

编辑:

好的,所以我试过这个:

 $directory = "admin/";
 $current = $directory . basename($_SERVER["SCRIPT_FILENAME"]);
 $redirect[] = "page1.php";
 $redirect[] = "page2.php";
 $redirect[] = "admin/index.php";
 if(in_array($current, $redirect)) {
  header("Location: http://example.com/index.php");
}

我手动将目录添加到最后redirect[]值。

然后我添加了一个$current变量,它输出当前脚本名称admin/,例如`admin / index.php'。

我的假设是它会在http://example.com/admin/index.php处重定向某个页面,但它也会重定向http://example.com/index.php

我想重定向目录admin中的所有文件,但文件必须位于数组中,这样才能重定向admin目录中的某些文件。此代码段位于我的配置文件中,并包含在每个页面中。

http://example.com/admin/index.php应重定向,但http://example.com/index.php不应重定向。

2 个答案:

答案 0 :(得分:1)

如果您只想重定向,如果当前文件位于admin目录中,并且该文件也位于/^(.+[\\\/])?(?=[^\\\/]+_DIRECTIVE)/ ^ at the start of the string ( )? match an optional group .+ with 1 or more characters [\\\/] and ending with a directory separator (\ or /) (?= ) followed by a group which is excluded from the match [^\\\/]+ which has a folder-name (no \, /) _DIRECTIVE followed by a literal _DIRECTIVE 数组中,那么您也可以通过两部分执行此操作:

$redirect

答案 1 :(得分:0)

鉴于您当前的脚本,您可以为每个值添加$ directory,如下所示:

 $directory = "admin/";
 $redirect[] = array();
 $redirect[] = $directory . "page1.php";
 $redirect[] = $directory . "page2.php";
 $redirect[] = $directory . "index.php";
 if(in_array($directory . basename($_SERVER["SCRIPT_FILENAME"]), $redirect)) {
  header("Location: http://example.com/index.php");
}

然后稍后在脚本中添加另一个(动态)数组项:

$redirect[] = $directory . $varStoringAnotherFilename;

或者您可以使用array_map创建辅助函数并一次性修改所有现有值:

function setDirectory($file) {
  return "admin/" . $file;
}

 $redirect[] = array();
 $redirect[] = "page1.php";
 $redirect[] = "page2.php";
 $redirect[] = "index.php";
 if(in_array($directory . basename($_SERVER["SCRIPT_FILENAME"]), array_map('setDirectory', $redirect))) {
  header("Location: http://example.com/index.php");
}

但是在你的条件下跳过$目录会更容易:

 $redirect[] = array();
 $redirect[] = "page1.php";
 $redirect[] = "page2.php";
 $redirect[] = "index.php";
 if(in_array(basename($_SERVER["SCRIPT_FILENAME"]), $redirect)) {
  header("Location: http://example.com/index.php");
}