Crays
Crays

Reputation: 2508

renaming array from value

i have a string, say its

ID=14,123@@ID=15,789@@

i exploded it with

$pieces = explode("@@", $contents);

so now i have a set of array

array(3) 
{ 
[0]=> string(69) "ID=14,123" 
[1]=> string(9) "ID=15,789" 
[2]=> string(0) "" 
}

then i would like to explode again the string within the array and used this

foreach ($pieces as $key => $value){
     $pieces[$key] = strpos( $value, "," ) ?
                explode( ",", $value ) :
                $value; 

     }

now i have an even more nested one

array(3) 
{ 
[0]=> array(2) 
   { 
   [0]=> string(5) "ID=14" 
   [1]=> string(3) "123" 
   } 
[1]=> array(2) 
   { 
   [0]=> string(5) "ID=15" 
   [1]=> string(3) "789" 
   } 
[2]=> string(0) 
   "" 
}

but what i wanted was so that the word "ID" can be replaced into the key of the array so it becomes

array 
{ 
[ID=14]=> "123" 
[ID=15]=> "789" 
}

how can that be done? i'm very unfamiliar with array but would love to learn.

Upvotes: 0

Views: 63

Answers (2)

David
David

Reputation: 3821

$contents = 'ID,123@@ID,789@@';
$pieces = explode("@@", $contents);

$parsed = array();
foreach ($pieces as $key => $value){
   $parsed[] = explode(',', $value);
}

$master = array();
foreach ($parsed as $ar) {
        $master[][$ar[0]] = $ar[1];
}
print_r($master);

Upvotes: 1

Alma Do
Alma Do

Reputation: 37365

You can not have same indexes. In case that you meant indexes inside arrays, this will do the stuff:

$string = 'ID,123@@ID,789@@';

$result = array_map(function($item)
{
   $temp = explode(',', $item);
   return count($temp)==2?[$temp[0] => $temp[1]]:$temp;
},explode('@@', $string));

//var_dump($result);

Upvotes: 1

Related Questions