2

I currently have an Array:

[1] => Array
    (
        [0] => 100011
        [1] => 1
    )

[2] => Array
    (
        [0] => 100013
        [1] => 1
    )

[3] => Array
    (
        [0] => 100022
        [1] => 1
    )

[4] => Array
    (
        [0] => 100025
        [1] => 1

I want to take the first child item (meaning [0]) of each array (1,2,3,4,etc) and put it into a new array. I know I need to loop through and assign the value to new array. Just not sure how to do it.

End result would be:

$final (name of new array) has values 100013,100022,100025,etc.

My real end result:

I need it kept in the same order, because I am then going to use array array_combine ( array $keys , array $values ) to create 100013 as the key and 1 as the value, 100022 as the key, 1 as the value, 100025 as the key, 1 as the value.

If you know a quicker way to accomplish, it is appreciated.

Thanks.

2
  • 4
    array_column($arr, 0) Commented Dec 18, 2014 at 15:34
  • @Ja͢ck genius. that did the trick. Commented Dec 18, 2014 at 15:40

3 Answers 3

10

If I understand you right, the final result can be obtained by doing:

array_combine(array_column($arr, 0), array_column($arr, 1));

Or, in a more traditional way:

$result = [];
foreach ($arr as list($key, $value)) {
    $result[$key] = $value;
}
Sign up to request clarification or add additional context in comments.

2 Comments

hi @Jack, Did u test speed between two this way with a large array?
@RyanNghiem no, but i would imagine that the modern way uses more memory for sure!
0
<?php
$results = array();
foreach($array as $item)
{
  $results[] = $item[0];
}
?>

Comments

0

if (PHP 5 >= 5.5.0)

 $first_names = array_column($records, 0);
 print '<pre>';
 print_r($first_names);

Another way,

function one_dimension($n) 
{
 return $n[0];
}

$result =array_map("one_dimension", $records);
print '<pre>';
print_r($result);

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.