Array manager
The Magento\Framework\Stdlib\ArrayManager library provides the ability to manage deeply nested associative arrays. The library is primarily used to handle data from UI components within DataProviders and Modifiers, which are actually part of a complicated process of parsing XML files in associative arrays.
Usage
existsfindfindPathsgetnull is returned if the node could not be found.movemergepopulateremovereplacesetslicePathExample 1
The following example shows how to add a custom field to the checkout billing address using the LayoutProcessor implementation.
<?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'];
...
}
...
}
For a cleaner implementation of the previous example, use the Magento\Framework\Stdlib\ArrayManager, library to eliminate duplicate checking and get the required array.
<?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)) {
...
}
...
}
...
Example 2
Suppose you have the following nested array:
$data = [
'response' => [
'status' => 'OK',
'result' => [
'items' => [
0 => 'First item',
1 => 'Second item',
...
],
...
]
]
]
You can use the Magento\Framework\Stdlib\ArrayManager library to access items in the array:
...
if ($this->arrayManager->get('response/status', $data) === 'OK') {
$items = $this->arrayManager->get('response/result/items', $data) ?? [];
foreach ($items as $item) {
...
}
}
...
You can use the Magento\Framework\Stdlib\ArrayManager library to populate an array from the given path:
...
$this->arrayManager->populate('response/result/items', $data)
...