0

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.

3
  • 3
    All the keys in an array must be unique. That's how arrays work. Commented Nov 6, 2013 at 14:23
  • In array { [ID]=> "123" [ID]=> "789" }; how will you call the value 789 and how can you distinguish it from 123? Commented Nov 6, 2013 at 14:25
  • thanks for clarification, what if i were to use ID=14, edited on original post. please have a look. Commented Nov 6, 2013 at 15:06

2 Answers 2

1
$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);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, indeed it is what i am looking for :) tho i really wish to learn, i can't seem to understand the phrase on foreach and within it. what does $pieces as $key => $value means actually? and $parsed[] would basically mean nothing right?
Yes. The $key=>$value isn't really necessary, but keeps me sane when doing foreach loops. $parsed is just a temporary array that holds the values.
1

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);

1 Comment

sorry array_map is not what i am looking for, as pointed out by the others, i've edited my question, could you please have a look, tq.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.