0

Please note that my php version is not 7. I have an array of arrays like:

array( 

    '0' => array('id'=>1,'name'=>'abc',"class"=>'xyz'),
    '1' => array('id'=>2,'name'=>'abc1',"class"=>'xyz1'),
    '2' => array('id'=>3,'name'=>'abc',"class"=>'xyz2'),
);

I want to extract it into two arrays. like

array( 

    '0' => array('id'=>1,'name'=>'abc'),
    '1' => array('id'=>2,'name'=>'abc1'),
    '2' => array('id'=>3,'name'=>'abc'),
);

array( 

    '0' => array('id'=>1,"class"=>'xyz'),
    '1' => array('id'=>2,"class"=>'xyz1'),
    '2' => array('id'=>3,"class"=>'xyz2'),
);

How can i achieve this, I am in search of some built-in function etc, I studied its supported with array_column but with versions higher than 7.

Edit: I also tried array_intersect_key and array_slice but its working with single dimensional array.

2
  • 1
    Apparently you didn't find the source of the information yet. The official PHP documentation is located at php.net/manual and it says that array_column() has been introduced in PHP 5.5. However, array_column() doesn't help for this problem. Commented Mar 27, 2018 at 14:43
  • So do it with a simple foreach loop over your original array Commented Mar 27, 2018 at 14:47

2 Answers 2

1

Then you might want to keep it simple and just use a straight forward foreach loop like this

$old = array( 
            array('id'=>1,'name'=>'abc',"class"=>'xyz'),
            array('id'=>2,'name'=>'abc1',"class"=>'xyz1'),
            array('id'=>3,'name'=>'abc',"class"=>'xyz2')
        );

foreach ( $old as $temp ) {
    $new1 = array('id' => $temp['id'], 'name' => $temp['name']);
    $new2 = array('id' => $temp['id'], 'class' => $temp['class']);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use a foreach and add the values to a new array for example:

$idsNames = [];
$idsClasses = [];
$items = [
    array('id' => 1, 'name' => 'abc', "class" => 'xyz'),
    array('id' => 2, 'name' => 'abc1', "class" => 'xyz1'),
    array('id' => 3, 'name' => 'abc', "class" => 'xyz2'),
];

foreach ($items as $item) {
    $idsNames[] = ["id" => $item["id"], "name" => $item["name"]];
    $idsClasses[] = ["id" => $item["id"], "class" => $item["class"]];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.