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] =>
)
)
)
)
Demo on 3v4l.org
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'))
]
];
Demo on 3v4l.org
A simple for loop can do it:
https://3v4l.org/h47MG
<?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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With