php - renaming array from value

680

i have a string, say its

ID=14,[email protected]@ID=15,[email protected]@

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.

513

Answer

Solution:

$contents = 'ID,[email protected]@ID,[email protected]@';
$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);
977

Answer

Solution:

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

$string = 'ID,[email protected]@ID,[email protected]@';

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

//var_dump($result);

People are also looking for solutions to the problem: php - Submitting comments to Wordpress without SSL /OAuth

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.