magento2中的数组管理器
7天成为Magento系统架构师,现在开始学习Magento全栈开发!
《Magento2.X企业级开发实战》
数组管理器
概述
Magento\Framework\Stdlib\ArrayManager库提供了管理深度嵌套关联数组的功能。该库主要用于处理来自DataProviders和Modifier中UI组件的数据,这实际上是解析关联数组中XML文件的复杂过程的一部分。
用法
METHOD | DESCRIPTION |
---|---|
exists | Checks if the node exists in a given associative array |
find | Finds a node in a nested array and saves its index and parent node reference |
findPaths | Gets matching paths for elements with specified indexes. |
get | Returns the value of the key (or node) at the end of the path. null is returned if the node could not be found. |
move | Moves a value from one path to another |
merge | Merges a value with a node and returns the modified data. |
populate | Populates a nested array, if possible and necessary. |
remove | Removes a node and returns the modified array. |
replace | Updates the existing nodes and returns the modified array |
set | Sets the value into a node and returns modified data. |
slicePath | Retrieves a slice of the specified path. |
例1
下面的示例演示如何使用LayoutProcessor实现将自定义字段添加到签出账单地址。
<?php /** * Process js Layout of block * * @param array $jsLayout * * @return array */ public function process($jsLayout) { ... if (isset($jsLayout['components']['checkout']['children']['steps']['children']['shipping-step'] ['children']['shippingAddress']['children']['shipping-address-fieldset']['children']) ) { $fields = $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step'] ['children']['shippingAddress']['children']['shipping-address-fieldset']['children']; ... } ... }
为了更清晰地实现上一个示例,请使用Magento\Framework\Stdlib\ArrayManager库消除重复检查并获取所需的数组。
<?php use Magento\Framework\Stdlib\ArrayManager; ... /** * @var ArrayManager */ private $arrayManager; /** * SomeClass constructor. * * @param ArrayManager $arrayManager */ public function __construct(ArrayManager $arrayManager) { $this->arrayManager = $arrayManager; } /** * Process js Layout of block * * @param array $jsLayout * * @return array */ public function process($jsLayout): array { $path = 'components/checkout/children/steps/children/shipping-step/children/shippingAddress/children/shipping-address-fieldset/children'; if ($fields = $this->arrayManager->get($path, $jsLayout)) { ... } ... } ... 示例二: 假设您有以下嵌套数组: $data = [ 'response' => [ 'status' => 'OK', 'result' => [ 'items' => [ 0 => 'First item', 1 => 'Second item', ... ], ... ] ] ] ...
您可以使用Magento\Framework\Stdlib\ArrayManager库访问数组中的项: ... if ($this->arrayManager->get('response/status', $data) === 'OK') { $items = $this->arrayManager->get('response/result/items', $data) ?? []; foreach ($items as $item) { ... } }
您可以使用Magento\Framework\Stdlib\ArrayManager库从给定路径填充数组:
... $this->arrayManager->populate('response/result/items', $data) ...
如无特殊说明或标注,任何个人或组织,复制、转载、采集本站内容请注明:
本文来源于:【Magento中文网】,并添加本文地址链接。
如未按上述操作复制或转载,本站有权追究法律责任。
若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
本文来源于:【Magento中文网】,并添加本文地址链接。
如未按上述操作复制或转载,本站有权追究法律责任。
若本站内容侵犯了原著者的合法权益,可联系我们进行处理。