1

I have the following array, which has some extra character in the value "/".

Array
(
    [ID1] => 362/2
    [ID2] => 589/3
    [ID3] => 697/4
    [ID4] => 111/5
    [ID5] => 422/6
)

what I want to achieve and get is as follows

Array
(
    [ID1] => 362
    [ID1] => 2
    [ID2] => 589
    [ID2] => 3
    [ID3] => 697
    [ID3] => 4
    [ID4] => 111
    [ID4] => 5
    [ID5] => 422
    [ID5] => 6
)

And, I have tried to write script in php to solve the above issues...

        $exp = array();
        foreach ($value as $val) {
            $pl = explode('/', $val);
            $exp[] = $pl[0] ."=>".$pl[1];
        }

         print_arr($exp);

But, I got the following result, In which it is wrong...

Array
(
    [0] => 362=>2
    [1] => 589=>3
    [2] => 697=>4
    [3] => 111=>5
    [4] => 422=>6
)

how do I do it? some help please?

1
  • What you want to achieve is not possible because keys must be unique. With that restriction in mind, perhaps some other alternative would suit you? Commented Oct 3, 2013 at 10:54

2 Answers 2

1

It is impossible to have multiple values with the same key.

Probably the best solution for you should be:

$exp = array();
foreach ($value as $id => $val) {
  list($first, $second) = explode('/', $val);
  $exp[$id] = array(
    'first'  => $first,
    'second' => $second
  );
}

So in the output you will have:

array(
  'id1' => array(
    'first'  => 362,
    'second' => 2
  ),
  ...
)
Sign up to request clarification or add additional context in comments.

3 Comments

That is perfect answer for me, thanks for your cooperation, I accept is as answer.
but one more question, if I need to search 2 in this array, how do I do that?
What for do you want to search ?
1
$exp = array();
$i=1;
    foreach ($value as $val) {
        $pl = explode('/', $val);
        $exp['id'.$i][] = $pl[0];
        $exp['id'.$i][] = $pl[1]; 
        $i++;
    }

Your expected array has duplicate Keys which is not possible

Comments

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.