Skip to content

Instantly share code, notes, and snippets.

@loilo
Created October 24, 2018 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loilo/09c64d9b2f7f367d5024a37794ee91c8 to your computer and use it in GitHub Desktop.
Save loilo/09c64d9b2f7f367d5024a37794ee91c8 to your computer and use it in GitHub Desktop.
Structural Extraction of PHP Arrays

Structural Extraction of PHP Arrays

Extract structures from PHP arrays, kind of like an advanced pluck.

Signature

The provided xtract function takes a $source (usually an array) and a $target, which is the structure to transform the $source into:

mixed xtract( mixed $source, mixed $target )

Simple Examples

xtract([ 1, 2, 3 ], [ 0, 1 ]) === [ 1, 2 ];

// The asterisk is a special token, translating to "anything"
xtract([ 1, 2, 3 ], '*') === [ 1, 2, 3 ];

Advanced Examples

$source = [
    'a' => [
        'd' => 3,
        'e' => 4
    ],
    'b' => [
        'd' => 5,
        'e' => 6
    ],
    'c' => [
        'd' => 7,
        'e' => 8
    ]
];

xtract($source, [ 'a' ])
===
[
    'a' => [
        'd' => 3,
        'e' => 4
    ]
];

xtract($source, [ '*' => [ 'd' ] ])
===
[
    'a' => [ 'd' => 3 ],
    'b' => [ 'd' => 5 ],
    'c' => [ 'd' => 7 ]
];
<?php
function xtract($source, $target)
{
if ($target === '*') {
return $source;
}
$result = [];
if (sizeof($target) === 1 && isset($target['*'])) {
foreach ($source as $k => $v) {
$result[$k] = xtract($v, $target['*']);
}
} else {
$i = 0;
foreach ($target as $k => $v) {
$nested = $i !== $k;
$key = $nested ? $k : $v;
if (isset($source[$key])) {
$result[$key] = $nested
? xtract($source[$key], $v)
: $source[$key];
}
if (!is_string($k)) {
$i++;
}
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment