duanlisha2335 2012-05-08 18:47
浏览 66
已采纳

从文件中读取数组键,不包括该文件

I have a php file that contains an array $myArray.

<?php 
$myArray = array(
  'key1'=>'value1',
  'key2'=>'value2',
);
?>

I need to read the value of key1 from that array. Is there a way to directly read key1, without including the whole file? Right now I'm using include like this.

$includedArray = include('/path/to/myArray.php');

but this is creating a problem for me, because even though I include it under a new name $includedArray, it still recognizes the old name $myArray which causes naming conflicts.

To solve this problem, I would have changed the included array from a named array ($myArray) to an un-named array, but I can't make changes to the included files. So is there a way to either:

  • include the file containing the named array, but have it completely forget the original name ($myArray), and have it use ONLY the new name I give it ($includedArray)?

  • or is there a way to simply read 1 key from the array without including the whole file?

  • 写回答

4条回答 默认 最新

  • doumie7914 2012-05-08 19:01
    关注

    Then copy the array to another variable and unset the original array?

    path/to/myNewArray.php:

    return call_user_func(function() {
      include "/path/to/myArray.php";
      return $myArray;
    });
    
    /*
    if (isset($myArray)) {
      $tmpMyArray = $myArray; // storing the $myArray if defined
    }
    
    $includedArray = $myArray;
    unset($myArray);
    if (isset($tmpMyArray)) {
      $myArray = $tmpMyArray; // restoring the previous $myArray
    }
    */
    

    usage:

    $whatEver = include("/path/to/myNewArray.php"); // no interference now
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀