Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have an array:

$ar = array(
 0 => array('id' => '1', 'pname' => 'text'),
 1 => array('id' => '2', 'pname' => 'text2'),
 2 => array('id' => '2', 'pname' => 'text3'),
 3 => array('id' => '3', 'pname' => 'text4'),
 4 => array('id' => '4', 'pname' => 'text5'),
 5 => array('id' => '4', 'pname' => 'text6'),
 6 => array('id' => '4', 'pname' => 'text7'),

);

I want to get array like this:

$result = array(
 0 => array('id' => '1', 'pname' => 'text'),
 1 => array('id' => '2', 'pname' => array('text2', 'text3')),
 3 => array('id' => '3', 'pname' => 'text4'),
 4 => array('id' => '4', 'pname' => array('text5', 'text6', 'text7'))
);

need help! how to iterate first array to get result like second array?

share|improve this question

closed as off-topic by Dainis Abols, deceze, André Dion, devnull, Nikos Paraskevopoulos Nov 19 '13 at 13:56

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist" – Dainis Abols, deceze, André Dion, devnull, Nikos Paraskevopoulos
If this question can be reworded to fit the rules in the help center, please edit the question.

3  
Have you tried something? –  putvande Nov 19 '13 at 9:47
    
How does your code looks now? What are the problems, you are getting with it? –  Dainis Abols Nov 19 '13 at 9:49
    
Shall we code for you... Paste your try also.. –  Nisar Nov 19 '13 at 9:52

1 Answer 1

up vote 4 down vote accepted

Simple foreach loop should do the trick, eg:

$array_1 = array(
    array('id' => '1', 'pname' => 'text'),
    array('id' => '2', 'pname' => 'text2'),
    array('id' => '2', 'pname' => 'text3'),
    array('id' => '3', 'pname' => 'text4'),
    array('id' => '4', 'pname' => 'text5'),
    array('id' => '4', 'pname' => 'text6'),
    array('id' => '4', 'pname' => 'text7'),
);

$iterated_array = array();
foreach ($array_1 as $value) {
    $iterated_array[$value['id']]['pname'][] = $value['pname'];
}

print_r($iterated_array);
share|improve this answer
1  
And to prove that it works: codepad.org/3265fUl6 –  Casper André Casse Nov 19 '13 at 9:51

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