I have a pretty complicated array operation, or at least it is complicated for me. Lets say I got such kind of array
$myArr['url_1']['linktypes']['follow'] = 10;
$myArr['url_1']['linktypes']['nofollow'] = 20;
$myArr['url_1']['linktypes']['other'] = 30;
$myArr['url_2']['linktypes']['follow'] = 40;
$myArr['url_2']['linktypes']['nofollow'] = 50;
$myArr['url_2']['linktypes']['other'] = 60;
$myArr['url_3']['linktypes']['follow'] = 70;
$myArr['url_3']['linktypes']['nofollow'] = 80;
$myArr['url_3']['linktypes']['other'] = 90;
and simply (!) I need to get following result
array(
array("id"=>1,"metric"=>'follow','url_1'=>10,'url_2'=>40,'url_3'=>70),
array("id"=>2,"metric"=>'nofollow','url_1'=>20,'url_2'=>50,'url_3'=>80),
array("id"=>3,"metric"=>'other','url_1'=>30,'url_2'=>60,'url_3'=>90)
);
These array elements are created dynamicall from $myArr. I have tried many ways but I failed many times. Hopefully someone has a short, simple logic to solve this.
Thanks.
Edit: This one is my shortest try. I have many different ways but this code is a part of big code structure, example you see here is created to simplify the logic I need.
$linkStructure = array();
foreach($myArr as $links=>$value){
$counter = 0;
foreach($value['linktypes'] as $ltKey => $ltValue){
if($linkStructure[$counter]["id"] && $linkStructure[$counter]["metric"] == $ltKey){
$linkStructure[$counter][$links] = $ltValue;
}
else{
$linkStructure[$counter]["id"] = $counter;
$linkStructure[$counter]["metric"] = $ltKey;
$linkStructure[$counter][$links] = $ltValue;
}
}
}
I swear I tried how I can prove better I don’t know. Don’t torture please. If you have any idea just share, is it too much I’m asking for?
I can’t explain this very well, so I’m just going to use code:
That should do it.
But I should say that the comments are right, a better way to structure your array would be like this:
Basically the same way you have it originally, but with fewer dimensions. This is all that you need for the data you have provided.