我正在使用 SPLFile 类创建 CSV 文件:
$z=new SplFileObject('/tmp/test.csv.gz','w');
$arr=[['a','b','c'],[1,2,3],[2,4,8],[3,6,9]];
foreach($arr as $f) $z->fputcsv($f);
Run Code Online (Sandbox Code Playgroud)
有没有办法 gz 压缩我的输出?
谢谢
通用汽车
我有一个实现ArrayAccess,Iterator和Countable的对象.这产生了一个非常完美的阵列掩蔽.我可以使用offsets($object[foo])访问它,我可以将它放入foreach-loop和许多其他东西.
但我不能做的是把它交给本地阵列迭代器函数(next(),reset(),current(),key()),即使我已经实现了从迭代器所需要的方法.PHP似乎顽固地试图遍历其成员变量,并完全忽略迭代器方法.
是否有一个接口可以将对象挂钩到剩余的数组遍历函数,还是我坚持使用我拥有的东西?
更新: IteratorAggregate似乎也不是答案.虽然它在foreach-loops中使用,但基本数组迭代器函数不会调用方法.
    $base = dirname(__FILE__).'/themes/';
    $target = dirname( STYLESHEETPATH ).'/';
    $directory_folders = new DirectoryIterator($base); 
    foreach ($directory_folders as $folder) 
    {
        if (!$folder->isDot())           {
            echo '<p>source: '.$folder->getRealPath();
            //returns: C:\xampplite\htdocs\test\wp-content\plugins\test\themes\testtheme-1
            echo '<br>target: '.$target;
            //returns: C:\xampplite\htdocs\test/wp-content/themes/
            copy($folder->getRealPath(), $target);
            //returns: Error. The first argument to copy() function cannot be a directory
         }
    }die;
Run Code Online (Sandbox Code Playgroud)
更新:关于Pascal建议的答案,这是我修改过的代码.这有效.
function recurse_copy(){
    $src = dirname(__FILE__).'/themes/';
    $dst = dirname( STYLESHEETPATH ).'/';
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) 
    { 
        if (( $file != '.' ) && ( $file != '..' …Run Code Online (Sandbox Code Playgroud) 我有一个Logger接口,SplFileObject在构造函数中接受一个用作该特定日志的文件.还有log($timestamp, $message)一种可用于实际记录的方法.在我的第一个实现中,当实例化一个新对象并传递一个只读时,SplFileObject应抛出一个异常.我写了一个合适的单元测试:
<?php
class FileLoggerTest extends PHPUnit_Framework_TestCase {
    /**
     * @expectedException \InvalidArgumentException
     */
    public function testReadOnlyFileObjectFailure() {
        $file = '/Library/WebServer/Documents/sprayfire/tests/mockframework/logs/test-log.txt';
        $LogFile = new \SplFileObject($file);
        $Logger = new \libs\sprayfire\logger\FileLogger($LogFile);
        $Logger->log('test', 'something');
    }
}
?>
Run Code Online (Sandbox Code Playgroud)
通常我会有一个生成目录名的方法,但是当我开始遇到问题时,我将其更改为绝对路径以排除原因.
这是实施:
namespace libs\sprayfire\logger;
use \SplFileObject as SplFileObject;
use \InvalidArgumentException as InvalidArgumentException;
use libs\sprayfire\logger\Logger as Logger;
    /**
     * @brief A framework implemented class that adds a timestamp log message to
     * the end of an injected file.
     */
    class …Run Code Online (Sandbox Code Playgroud) 我正在使用这个脚本,但我想指定递归函数的最大深度.我不知道如何使用它,我总是得到一个错误.我该如何在这里使用:: setMaxDepth?
public function countFiles($path)
{ 
global $file_count;
$depth=0;
$ite=new RecursiveDirectoryIterator($path);
$file_count=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) :
    $file_count++;
    $files[] = $filename;
endforeach;
return $file_count;
}
Run Code Online (Sandbox Code Playgroud) 我使用SplFileObject和LimitIterator来读取大文件中从位置 x 到 y 的内容。
当使用像/home/devel/stuff/myfile.log.
当使用这样的路径时,http://mydomain.com:8090/devel/stuff/myfile.log它不起作用。不过路径是正确的。
使用绝对路径时会失败吗?
错误消息是:
PHP Warning:  SplFileObject::rewind() [<a href='splfileobject.rewind'>splfileobject.rewind</a>]: stream does not support seeking in ...
PHP Fatal error:  Uncaught exception 'RuntimeException' with message 'Cannot rewind file ...'
完整代码:
  // $pStrFile contains the valid (yes!) path
  $oFile = new SplFileObject($pStrFile);
  // $nFrom = 80 and $nLines = 30
  $fileIterator = new LimitIterator($oFile, $nFrom, $nLines);
  foreach($fileIterator as $line) {
      $strLines .= $line;
  }
Run Code Online (Sandbox Code Playgroud) 我试图理解ArrayAccess接口背后的想法,
我不明白每个方法的含义,如果那些方法(函数)是"内置"函数而ArrayAccess接口(也是"内置")只是"确保"我将实现那些"内置"方法(函数) )
我试图理解每个函数在我们的代码"幕后花絮"中做了什么.
function offsetSet($offset, $value);
function offsetGet($offset);
function offsetUnset($offset);
function offsetExists($offset);
Run Code Online (Sandbox Code Playgroud)
如果我理解ArrayAccess是一个内置接口,包含要实现的密封,当我们实现它们时,我们只实现对内置函数的引用,如果有人能帮助我做到这一点,我将很高兴.
我在PHP手册中阅读了IteratorAggregate的示例.我尝试删除IteratorAggregate接口,但输出与实现的类似.
<?php    
    class myData {
        public $property1 = "Public property one";
        public $property2 = "Public property two";
        public $property3 = "Public property three";
        public function __construct() {
            $this->property4 = "last property";
        }
    }
    $obj = new myData;
    foreach($obj as $key => $value) {
        var_dump($key, $value);
        echo "\n";
    }
Run Code Online (Sandbox Code Playgroud)
输出:
string(9) "property1"
string(19) "Public property one"
string(9) "property2"
string(19) "Public property two"
string(9) "property3"
string(21) "Public property three"
string(9) "property4"
string(13) "last property"
Run Code Online (Sandbox Code Playgroud)
我想知道我们何时应该实现IteratorAggregate接口?为什么输出是相同的?
spl_object_hash()在这种情况下,我正在了解并且不太了解幕后的内容:
$obj = new stdClass;
$id1 = spl_object_hash($obj);
$id2 = spl_object_hash(new stdClass);
echo $id1.'<br>'.$id2;
Run Code Online (Sandbox Code Playgroud)
一季度。为什么$id1 !== $id2?
在参考资料中:
当一个对象被销毁时,它的散列值可能会被其他对象重用。
Q.2 是否有与该声明相关的内容?还是我错过了其他东西?
如何找到已加载到EnterpriseDB中的语言(PL/pgsql,SPL,Java)?如果有人知道在PostgreSQL上找到加载语言的方法,那么EnterpriseDB建立在PostgreSQL之上.它应该工作相同.
基本上,我想使用
$foo = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack));
Run Code Online (Sandbox Code Playgroud)
方法,但不是返回一个平面数组foreach()来保持结构,而是只返回一个伟大的大子节点和它的父节点.这可能在PHP?
我的任务是优化我公司的一些(可怕的)代码库.我发现了一个通过数组递归,搜索密钥的函数.我不能用一个简单的替换它,array_search()或者array_key_exists()因为自定义函数也返回匹配(找到)键的父节点,而不是只返回一个true或false.
如何使用RecursiveArrayIterator,RecursiveIteratorIterator或做不到这一点,其他内置功能(即尽可能少的自定义代码越好)返回匹配的节点与它的父树从搜索阵列?我想获得最快的功能,因为目前这个功能花费8秒执行14000次,因此我需要使用内置函数.
我现有的尝试(下面)非常缓慢.
function search_in_array($needle, $haystack) {
    $path = array();
    $it = new RecursiveArrayIterator($haystack);
    iterator_apply($it, 'traverse', array($it, $needle, &$path));
    return $path;
}
function traverse($it, $needle, &$path) {
    while($it->valid()) {
        $key = $it->key();
        $value = $it->current();
        if(strcasecmp($value['id'], $needle) === 0) {
            $path[] = $key;
            return;
        } else if($it->hasChildren()) {
            $sub = null;
            traverse($it->getChildren(), $needle, &$sub);
            if($sub) {
                $path[$key] …Run Code Online (Sandbox Code Playgroud) 看来我不能通过引用迭代SplFixedArray中的值:
$spl = new SplFixedArray(10);
foreach ($spl as &$value)
{
    $value = "string";
}
var_dump($spl);
Run Code Online (Sandbox Code Playgroud)
输出:
Fatal error: Uncaught exception 'RuntimeException' with message 'An iterator cannot be used with foreach by reference'
Run Code Online (Sandbox Code Playgroud)
任何解决方法?
我一直在做相当多的研究,我得出的结论是,我宁愿用愚蠢的旧东西实现一切,scandir而foreach不是采用迭代器的方式.
基本上,我需要一种获取目录内容的方法 - 可选择排序,可选地递归,并可选择按文件名过滤.哪个IMO是您期望从任何有些复杂的文件系统遍历中获得的最基本功能.
事实证明,既不支持RecursiveDirectoryIterator也不FilesystemIterator支持排序或过滤.必须将它们包装在一个扩展ArrayObject为实现排序的类中,或者FilterIterator用于过滤.因此,为了实现这两个目标,你必须编写两个类,将所有内容包装在无数级别中,并且代码最终会看起来异乎寻常并且过于复杂.
我错过了关于这种方法的一些内容,还是应该抓住我的进度并用简单的愚蠢if/else/foreach代码重写20多行内容?
spl ×13
php ×12
arrays ×2
arrayaccess ×1
copy ×1
csv ×1
enterprisedb ×1
file-io ×1
gzip ×1
hashcode ×1
metadata ×1
optimization ×1
phpunit ×1
plpgsql ×1
postgresql ×1
recursion ×1