框架 php_【php框架开发】Laravel框架之PHP对象遍历

6714b9fbf6b9224502a218c1a495238e.gif

b1ce1d314b5a2c7fee19ab809fb22343.png

本文主要学习:Laravel框架之PHP对象遍历(Iterator),小编把自己的一点点经验分享出来希望对别人能有帮助。同时,作者会将开发过程中的一些截图和代码黏上去,提高阅读效率。

0b5bfd4576e4d2b116b6d659811f94a7.png

说明:本文章主要讲述PHP的对象遍历(Iterator)知识点。由于Laravel框架中就在集合(Collection)中用到了对象遍历知识点,故记录并学习之。

Laravel中在基础集合类

Illuminate\Support\Collection、路由类中Illuminate\Routing\RouteCollection和分页类中Illuminate\Pagination\Paginator等,都用到了对象遍历这个小知识点,这些类都是实现了IteratorAggregate这个接口,这个接口定义getIterator(),返回的是迭代器对象。PHP标准扩展库中提供了很多默认迭代器实现类,比较常用的是数组迭代器对象ArrayIterator

对象遍历(Iterator) 基本遍历

PHP5提供了遍历对象属性的方法,而且默认是可见属性,如代码中foreach遍历对象属性,默认的都是可见属性:

<?php /**  * Created by PhpStorm.  * User: liuxiang  * Date: 16/7/20  * Time: 17:29  */ class TestIterator {     /**      * @var string      */     public $name    = 'PHP';     /**      * @var string      */     public $address = 'php.net';     /**      * @var string      */     protected $sex  = 'man';     /**      * @var int      */     private $age    = 20; } $testIterator = new TestIterator(); foreach ($testIterator as $key => $value) {     echo $key.':'.$value.PHP_EOL; } 输出的是: name:PHP address:php.net 如果需要遍历对象的不可见属性,则在对象内部定义一个遍历方法: public function unAccessIterator()     {         echo 'Iterator the unaccess fields:'.PHP_EOL;         foreach ($this as $key => $value) {             echo $key.':'.$value.PHP_EOL;         }     } 对象外部访问: $testIterator->unAccessIterator(); 将可以遍历对象的不可见属性,输出结果: Iterator the unaccess fields: name:PHP address:php.net sex:man age:20 Iterator接口

PHP提供了Iterator接口,用来定义迭代器对象来自定义遍历,所以利用Iterator接口来构造迭代器,需要实现Iterator定义的几个方法:

/**

 * Created by PhpStorm.

 * User: liuxiang

 * Date: 16/7/20

 * Time: 17:29

 */

class TestIterator implements Iterator{

    /**

     * @var string

     */

    public $name    = 'PHP';

    /**

     * @var string

     */

    public $address = 'php.net';

    /**

     * @var string

     */

    protected $sex  = 'man';

    /**

     * @var int

     */

    private $age    = 20;

    /**

     * @var array

     */

    private $composerPackage;

    public function __construct($composerPackage = [])

    {

        $this->composerPackage = $composerPackage;

    }

    public function unAccessIterator()

    {

        echo 'Iterator the unaccess fields:'.PHP_EOL;

        foreach ($this as $key => $value) {

            echo $key.':'.$value.PHP_EOL;

        }

    }

    /**

     * Return the current element

     * @link http://php.net/manual/en/iterator.current.php

     * @return mixed Can return any type.

     * @since 5.0.0

     */

    public function current()

    {

        // TODO: Implement current() method.

        echo 'Return the current element:'.PHP_EOL;

        return current($this->composerPackage);

    }

    /**

     * Move forward to next element

     * @link http://php.net/manual/en/iterator.next.php

     * @return void Any returned value is ignored.

     * @since 5.0.0

     */

    public function next()

    {

        // TODO: Implement next() method.

        echo 'Move forward to next element:'.PHP_EOL;

        return next($this->composerPackage);

    }

    /**

     * Return the key of the current element

     * @link http://php.net/manual/en/iterator.key.php

     * @return mixed scalar on success, or null on failure.

     * @since 5.0.0

     */

    public function key()

    {

        // TODO: Implement key() method.

        echo 'Return the key of the current element:'.PHP_EOL;

        return key($this->composerPackage);

    }

    /**

     * Checks if current position is valid

     * @link http://php.net/manual/en/iterator.valid.php

     * @return boolean The return value will be casted to boolean and then evaluated.

     * Returns true on success or false on failure.

     * @since 5.0.0

     */

    public function valid()

    {

        // TODO: Implement valid() method.

        echo 'Checks if current position is valid:'.PHP_EOL;

        return current($this->composerPackage) !== false;

    }

    /**

     * Rewind the Iterator to the first element

     * @link http://php.net/manual/en/iterator.rewind.php

     * @return void Any returned value is ignored.

     * @since 5.0.0

     */

    public function rewind()

    {

        // TODO: Implement rewind() method.

        echo 'Rewind the Iterator to the first element:'.PHP_EOL;

        reset($this->composerPackage);

    }

}

/*

$testIterator = new TestIterator();

foreach ($testIterator as $key => $value) {

    echo $key.':'.$value.PHP_EOL;

}

$testIterator->unAccessIterator();*/

$testIterator = new TestIterator([

    'symfony/http-foundation',

    'symfony/http-kernel',

    'guzzle/guzzle',

    'monolog/monolog'

]);

foreach ($testIterator as $key => $value) {

    echo $key.':'.$value.PHP_EOL;

}

成员变量$composerPackage是不可见的,通过实现Iterator接口,同样可以遍历自定义的可不见属性,输出结果如下:

Rewind the Iterator to the first element:

Checks if current position is valid:

Return the current element:

Return the key of the current element:

0:symfony/http-foundation

Move forward to next element:

Checks if current position is valid:

Return the current element:

Return the key of the current element:

1:symfony/http-kernel

Move forward to next element:

Checks if current position is valid:

Return the current element:

Return the key of the current element:

2:guzzle/guzzle

Move forward to next element:

Checks if current position is valid:

Return the current element:

Return the key of the current element:

3:monolog/monolog

Move forward to next element:

Checks if current position is valid:

ed7782cf71059319c2d316efb6a3dc6b.png IteratorAggregate接口

PHP真心为程序员考虑了很多,实现IteratorAggragate接口后只需实现getIterator()方法直接返回迭代器对象,就不需要实现Iterator接口需要的一些方法来创建一些迭代器对象,因为PHP已经提供了很多迭代器对象如ArrayIterator对象。所以再重构下上面代码:

class TestCollection implements IteratorAggregate{

    ...

    /**

     * @var array

     */

    private $composerPackage;

    ...

    /**

     * Retrieve an external iterator

     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php

     * @return Traversable An instance of an object implementing Iterator or

     * Traversable

     * @since 5.0.0

     */

    public function getIterator()

    {

        // TODO: Implement getIterator() method.

        return new ArrayIterator($this->composerPackage);

    }

}

$testCollection = new TestCollection([

    'symfony/http-foundation',

    'symfony/http-kernel',

    'guzzle/guzzle',

    'monolog/monolog'

]);

foreach ($testCollection as $key => $value) {

    echo $key.':'.$value.PHP_EOL;

}

同样的,能遍历$testCollection对象的不可见属性$composerPackage,输出结果:

0:symfony/http-foundation

1:symfony/http-kernel

2:guzzle/guzzle

3:monolog/monolog

文章开头聊到Laravel中就用到了IteratorAggragate这个接口,可以看看文件的源码。

总结 PHP提供的对象遍历特性功能还是很有用处的。多多使用Laravel,研究Laravel源码并模仿之,也不错哦。

1

1

end

PHP网站开发教程,

php学习大本营的集合地。

早关注,早学习,早提升!

c9d79cfc725c7c21e76b5c2bf01e83ce.png 3485a681c26add7596f2802657c5ccf8.png

学习的路上,我们在等你

长按扫码可关注

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Laravel框架实现PHPExcel导入导出功能非常简单。首先,我们需要安装PHPExcel库。可以通过Composer来安装,只需在终端中运行以下命令: ``` composer require phpoffice/phpexcel ``` 安装完成之后,在Laravel的控制器中,我们可以使用PHPExcel的相关类来实现导入和导出功能。 要导出Excel文件,我们可以先创建一个PHPExcel对象,并设置一些基本的属性,例如文件名、作者等。然后,我们可以创建一个工作表,并设置一些表头信息。接下来,我们可以遍历需要导出的数据,将数据逐行写入工作表中。最后,我们可以使用PHPExcelWriter将工作表保存为Excel文件。下面是一个示例代码: ```php use PHPExcel; use PHPExcel_IOFactory; class ExportController extends Controller { public function exportData() { $objPHPExcel = new PHPExcel(); // 设置文件属性 $objPHPExcel->getProperties() ->setCreator("Your Name") ->setLastModifiedBy("Your Name") ->setTitle("Export Data") ->setSubject("Export Data") ->setDescription("Export Data"); $objPHPExcel->setActiveSheetIndex(0); $sheet = $objPHPExcel->getActiveSheet(); // 设置表头信息 $sheet->setCellValue('A1', 'Column 1') ->setCellValue('B1', 'Column 2') ->setCellValue('C1', 'Column 3'); // 导出数据 $data = [ ['Data 1', 'Data 2', 'Data 3'], ['Data 4', 'Data 5', 'Data 6'], ]; foreach ($data as $key => $value) { $row = $key + 2; $sheet->setCellValue('A' . $row, $value[0]) ->setCellValue('B' . $row, $value[1]) ->setCellValue('C' . $row, $value[2]); } // 导出Excel $objPHPExcel->getActiveSheet()->setTitle('Sheet 1'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('export.xlsx'); } } ``` 要导入Excel文件,我们可以先创建一个PHPExcel对象,并使用`load`方法加载Excel文件。然后,我们可以通过`getActiveSheet`方法获取工作表,并使用`getCell`方法获取单元格的值。接下来,我们可以遍历工作表的行和列,将数据存储到数组中。最后,我们可以对获取到的数据进行相关的处理。下面是一个示例代码: ```php use PHPExcel; use PHPExcel_IOFactory; class ImportController extends Controller { public function importData() { $objPHPExcel = PHPExcel_IOFactory::load('import.xlsx'); $sheet = $objPHPExcel->getActiveSheet(); $data = []; foreach ($sheet->getRowIterator() as $row) { $rowData = []; foreach ($row->getCellIterator() as $cell) { $rowData[] = $cell->getValue(); } $data[] = $rowData; } // 对导入的数据进行处理 // ... return $data; } } ``` 通过以上的代码,我们就可以轻松地在Laravel框架中实现PHPExcel的导入导出功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值