Edit:
Trying to avoid doing a loop outside of the $data
array you see. As I need to do this a couple of times and it looks messy.
I have got an array similar to this:
$links = [
[
'type_id' => '1',
'url' => ''
],
[
'type_id' => '2',
'url' => ''
]
];
$types = [
[
'id' => 1,
'value' => 'facebook'
],
[
'id' => 2
'value' => 'twitter'
]
];
$data = [
'primary' => [
'address_details' => [],
'contact_details' => [],
'social_links' => $links
]
];
I need the keys within my $data['primary']['social_links']
to use the $type['value']
rather than just being 0, 1, etc...
So $data
would look like:
$data = [
'primary' => [
'address_details' => [],
'contact_details' => [],
'social_links' => [
'facebook' => [
'type_id' => '1',
'url' => ''
],
'twitter' => [
'type_id' => '2',
'url' => ''
]
]
]
];
Is there a way I can do this with array_map
or something?
You can just use array_combine
with the output of the value
column of $types
(generated using array_column
) as keys and the values from $links
:
$data = [
'primary' => [
'address_details' => [],
'contact_details' => [],
'social_links' => array_combine(array_column($types, 'value'), $links)
]
];
print_r($data);
Output:
Array (
[primary] => Array (
[address_details] => Array ( )
[contact_details] => Array ( )
[social_links] => Array (
[facebook] => Array (
[type_id] => 1
[url] =>
)
[twitter] => Array (
[type_id] => 2
[url] =>
)
)
)
)
Update
Based on the edit to OPs question, things get a lot more complicated to give a one-line solution. This should work:
$data = [
'primary' => [
'address_details' => [],
'contact_details' => [],
'social_links' => array_map(function ($v) use ($links) { return $links[array_search($v, array_column($links, 'type_id'))]; }, array_column($types, 'id', 'value'))
]
];
A simple for
loop can do it:
<?php
$links = [
[
'type_id' => '1',
'url' => ''
],
[
'type_id' => '2',
'url' => ''
]
];
$types = [
[
'value' => 'facebook'
],
[
'value' => 'twitter'
]
];
$result = [];
for($i = 0, $len = count($types); $i < $len; $i++) {
$result[$types[$i]['value']] = $links[$i];
}
$data = [
'primary' => [
'address_details' => [],
'contact_details' => [],
'social_links' => $result
]
];
var_dump($data);
You could use a loop to modify the array directly :
for($i=0; $i < sizeof($links); $i++) {
$links[$types[$i]['value']] = $links[$i];
unset($links[$i]);
}
var_dump($links);
Output :
["facebook"]=> array(2) {
["type_id"]=> string(1) "1"
["url"]=> string(0) ""
}
["twitter"]=> array(2) {
["type_id"]=> string(1) "2"
["url"]=> string(0) ""
}
Or by using array_combine
if you do not want a loop, per your comment on another answer :
array_combine(array_column($types, 'value'), $links)
<pre><code>
$social_links = [];
foreach ($types as $type):
$social_links[$type['value']] = $links[$key];
endforeach;
$data = [
'primary' => [
'address_details' => [],
'contact_details' => [],
'social_links' => $social_links
]
];
print_r($data);
</code></pre>