Return Ids searching for the value of a multidimensional array

0

Is there any way without using foreach , using only native PHP functions to return an array with the ids fetching all that are with the 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 have the value 'a'

$lista_ids = array(100,5465);
    
asked by anonymous 11.07.2018 / 22:27

1 answer

0

I do not see why not use the 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 the array syntax, and doing with the 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 array_map in this way:

<?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 nulls that do not fall into the condition.

    
13.07.2018 / 15:57