1

I have this array that i need to edit the array :

    Array
(
    [E:\EasyPHP-cmsServer-14.1VC9\data\cms\sites\user_1\012014.user_1.txt] => TotalVisits 6788
    [E:\EasyPHP-cmsServer-14.1VC9\data\cms\sites\user_1\022014.user_1.txt] => TotalVisits 11141
    [E:\EasyPHP-cmsServer-14.1VC9\data\cms\sites\user_1\032014.user_1.txt] => TotalVisits 6143
    [E:\EasyPHP-cmsServer-14.1VC9\data\cms\sites\user_1\042014.user_1.txt] => TotalVisits 936
    [E:\EasyPHP-cmsServer-14.1VC9\data\cms\sites\user_1\052014.user_1.txt] => TotalVisits 936
    [E:\EasyPHP-cmsServer-14.1VC9\data\cms\sites\user_2\012014.user_2.txt] => TotalVisits 9
    [E:\EasyPHP-cmsServer-14.1VC9\data\cms\sites\user_2\022014.user_2.txt] => TotalVisits 25
    [E:\EasyPHP-cmsServer-14.1VC9\data\cms\sites\user_2\032014.user_2.txt] => TotalVisits 37
    [E:\EasyPHP-cmsServer-14.1VC9\data\cms\sites\user_2\042014.user_2.txt] => TotalVisits 17
    [E:\EasyPHP-cmsServer-14.1VC9\data\cms\sites\user_2\052014.user_2.txt] => TotalVisits 16
)

And I want to be like this :

Array
(
    [012014_user_1] => TotalVisits 6788
    [022014_user_1] => TotalVisits 11141
    [032014_user_1] => TotalVisits 6143
    [042014_user_1] => TotalVisits 936
    [052014_user_1] => TotalVisits 936
    [012014_user_2] => TotalVisits 9
    [022014_user_2] => TotalVisits 25
    [032014_user_2] => TotalVisits 37
    [042014_user_2] => TotalVisits 17
    [052014_user_2] => TotalVisits 16
)

Here's what I've tried :

foreach($myarray as $key => $value){
                        $exp_key = explode('\\', $key);
                        $exp_key_name = explode('.', $exp_key[6]);

                     $key = $exp_key_name[0]."_".$exp_key_name[1];

                    }

Any idea where's the error in my code? Thanks

2
  • 1
    You can't edit the key, but what you can do is make a new array. $newArray = array(), then in your current foreach: $newArray[$key] = $value.
    – gen_Eric
    May 21, 2014 at 17:05
  • You can also use basename to get your original array in the desired format to begin with, instead of using the whole file path. Or hey, use a database for this instead of text files.
    – Mog
    May 21, 2014 at 17:10

1 Answer 1

1

well simple solution is:

$array[$newkey] = $array[$oldkey];
unset($array[$oldkey]);

In your case you would loop through:

$newArray = array();
foreach($array as $key => $value) {
   $newKey = end(explode("\\", $key)); //need latest php for this otherwise split end and explode

   $newArray[$newKey] = $value;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.