Return Ids searching for the value of a multidimensional array

Asked

Viewed 42 times

0

Is there any way without using foreach, using only native PHP functions to return an array with ids searching everyone with value 'a' ?

Example:

$lista = array(
    array(
        'id' => '100',
        'name' => 'Sandra Shush',
        'value' => 'a'
    ),
    array(
        'id' => '5465',
        'name' => 'Stefanie Mcmohn',
        'value' => 'a'
    ),
    array(
        'id' => '40489',
        'name' => 'Michael',
        'value' => 'b'
    )
);

Return an array with the ids that has value 'a'

$lista_ids = array(100,5465);

1 answer

0


I don’t see why not use foreach, because when it comes to arrays with index it is a hand on the wheel. Foreach is native of PHP.

But let’s get down to business:

<?php

$lista = array(
    array(
        'id' => '100',
        'name' => 'Sandra Shush',
        'value' => 'a'
    ),
    array(
        'id' => '5465',
        'name' => 'Stefanie Mcmohn',
        'value' => 'a'
    ),
    array(
        'id' => '40489',
        'name' => 'Michael',
        'value' => 'b'
    )
);
$ids = [];
for($i = 0; $i < count($lista); $i++) {
    if( $lista[$i]['value'] == 'a' ) {
        $ids[] = $lista[$i]['id'];
    }
}

var_dump($ids);

Simplifying array syntax, and doing with foreach:

<?php

$lista = [
    [
        'id' => '100',
        'name' => 'Sandra Shush',
        'value' => 'a'
    ],
    [
        'id' => '5465',
        'name' => 'Stefanie Mcmohn',
        'value' => 'a'
    ],
    [
        'id' => '40489',
        'name' => 'Michael',
        'value' => 'b'
    ]
];
$ids = [];
foreach($lista as $item) {
    if ( $item['value'] == 'a' ) {
        $ids[] = $item['id'];
    }
}
var_dump($ids);

You can also do with the array_map thus:

<?php
function teste($item) {
    if($item['value'] == 'a') {
        return $item['id'];
    }
}

$lista = [
    [
        'id' => '100',
        'name' => 'Sandra Shush',
        'value' => 'a'
    ],
    [
        'id' => '5465',
        'name' => 'Stefanie Mcmohn',
        'value' => 'a'
    ],
    [
        'id' => '40489',
        'name' => 'Michael',
        'value' => 'b'
    ]
];
$b = array_map("teste", $lista);
echo '<pre>';
var_dump($b);
echo '</pre>';

The array_map will leave null those that do not enter the condition.

  • Thanks, the idea of not having to use the foreach was in case there was already something I write less without having to make a loop.

  • But the idea of loops is exactly this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.