K
K
kont_kont2016-11-28 11:40:07
PHP
kont_kont, 2016-11-28 11:40:07

How to parse a php array into pairs - key -> array element, value -> array / subarray element?

There is this array:

[ID] => 7204
[IBLOCK_SECTION_ID] => 142
[PROPERTY_VIRTUAL_SECTIONS_VALUE] => Array
        (
            [0] => 296
            [1] => 433
            [2] => 434
        )

There can be multiple [PROPERTY_VIRTUAL_SECTIONS_VALUE] elements. Get an array:
[7204] => Array
        (
            [0] => 142
            [1] => 296
            [2] => 433
            [3] => 434
        )

Or even easier, just
[0] => 142
[1] => 296
[2] => 433
[3] => 434

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2016-12-06
@TrogWarZ

Seriously? Question about how to work with arrays in PHP? Have you tried to solve it yourself?

<?php

// Test data

$in = [
    'ID'                              => 7204,
    'IBLOCK_SECTION_ID'               => 142,
    'PROPERTY_VIRTUAL_SECTIONS_VALUE' => [
        296,
        433,
        434,
    ],
];

$test = [
    7204 => [
        142,
        296,
        433,
        434,
    ],
];

// Working function
// 
function flattenConcreteArray (array $arr = []) : array {
    $id     = $arr['ID'];
    $result = [$arr['IBLOCK_SECTION_ID']];
    $result = array_merge($result, $arr['PROPERTY_VIRTUAL_SECTIONS_VALUE']);

    return [$id => $result];
};

// Testing

$out = flattenConcreteArray($in);

assert($out === $test);
echo 'It Works!' . PHP_EOL;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question