Hello there!
I try to create a function that return new array by keys mask from main array of properties.
It's like:
Client
$preparedParams = $request->prepareParams([
'name',
'price',
'description',
'tags',
], $request->params());
$request->params() - return array like below
[
'name' => 'iPhone',
'price' => 123,
'description' => 'Some desc',
'action' => 'add',
'page' => 'product',
'etc...' => '...',
]
Need for
$newProduct = new ModelProduct();
$newProduct->set($preparedParams);
$newProduct->save();
An easier solution
public function prepareParams(array $keys, array $values): array
{
$result = [];
foreach($keys as $key) {
$result[$key] = $values[$key] ?? null;
}
return $result;
}
Means that need include all params from keys mask including NULLs too
Second solution (may better?)
I've tried to do it without foreach, but not sure that the best way to do it.
public function prepareParams(array $keys, array $values): array
{
return array_merge(
$filledByKeys = array_fill_keys($keys, null),
array_intersect_key($values, $filledByKeys)
);
}
As you can see we create empty array with keys (it's first argument for merge). Then used intersect by key to get array that contains props from values (it's second argument for merge). And merged it with NULL keys.
But may you show better way for it?
Thank you!
CodePudding user response:
What about this? The loop is "hidden" by array_map ;)
edit: Oh... that's slightly wrong.. I'll correct edit2: updated to requirements.
$keys = [
'name',
'price',
'description',
'tags',
];
$src = [
'name' => 'iPhone',
'price' => 123,
'description' => 'Some desc',
'action' => 'add',
'page' => 'product',
'etc...' => '...',
];
$result = [];
array_map(function($key, $key2, $val) use (&$result) {
if ($key == $key2) {
$result[ $key ] = $val;
}
elseif($key != null) {
$result[ $key ] = null;
}
}, $keys, array_keys($src), array_values($src));
var_dump($result);
Output:
array(4) {
["name"]=>
string(6) "iPhone"
["price"]=>
int(123)
["description"]=>
string(9) "Some desc"
["tags"]=>
NULL
}
Does it meet your requirements?