Skip to content
Advertisement

Add keys in associative php array as per reference

I have an array, so I wanted to add keys to each value, for example, if an array contains Facebook URL then the key should be Facebook if an array has a link of Instagram then the key should be Instagram and the list goes on.

Here’s the code

<?php
foreach($social_media as $social){

$typesocial = $social['type'];
if($social['type'] === 'social network') {
$val[] = $social['url']['resource'];
}

}
print_r($val);

?>
Array ( 
[0] => https://plus.google.com/+beyonce
[1] => https://twitter.com/Beyonce
[2] => https://www.facebook.com/beyonce
[3] => https://www.instagram.com/beyonce/
[4] => http://www.weibo.com/beyonceofficial 
)

It should become, if the value has a link of twitter then the key should be twitter if Instagram then it should be Instagram

Array ( 
[google] => https://plus.google.com/+beyonce
[twitter] => https://twitter.com/Beyonce
[facebook] => https://www.facebook.com/beyonce
[instagram] => https://www.instagram.com/beyonce/
[weibo] => http://www.weibo.com/beyonceofficial 
)

Advertisement

Answer

This maybe? Hope to help

EDITED

$array = Array ( 
0 => 'https://plus.google.com/+beyonce',
1 => 'https://twitter.com/Beyonce',
2 => 'https://www.facebook.com/beyonce',
3 => 'https://www.instagram.com/beyonce/',
4 => 'http://www.weibo.com/beyonceofficial',
  6 => 'http://www.bbc.co.uk/a/witty/documentary'
);
$output = Array();
foreach($array as $key => $url){
 $urlarr = parse_url($url);
 $arr = explode('.',$urlarr['host']);
 $name =  $arr[count($arr) - 2];
  if($name == 'co'){
    $name =  $arr[count($arr) - 3]; 
  }
 $output[$name] = $url;
}
print_r($output);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement