C
C
CloudMonster2014-04-13 12:59:47
PHP
CloudMonster, 2014-04-13 12:59:47

How to get a specific element from an array?

Hello!
There is a very common array with cn elements. Each element has parameters such as:
ID:
TITLE:
TYPE:
COUNTER-ID:
VALUE:

Please tell me how can I get the VALUE of the last element from this array where COUNTER-ID = 14.
And the VALUE of the last element where COUNTER-ID = 15.
on php)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
W
wills0n, 2014-04-13
@CloudMonster

It is not kosher to sort arrays through for .

$resultArray = array();
foreach ($array as $element) {
$resultArray[$element['COUNTER-ID']] = $element;
}

echo $resultArray[14]['VALUE']; //VALUE последнего элемента, где COUNTER-ID = 14
echo $resultArray[15]['VALUE']; //VALUE последнего элемента, где COUNTER-ID = 15

C
Confl1kt, 2014-04-13
@Confl1kt

iterate over the array - if such a search is rarely used
if often - then make an array - counter-id => last key

$resultArray = [];
for($i = 0; $i< count($array); $i++){
    $resultArray[$array[$i]['COUNTER-ID']] = $i;
}
echo $resultArray[14]; // последний ключ в массиве для COUNTER-ID == 14
echo $array[$resultArray[14]]['VALUE']; //значение VALUE для последнего Counter-id == 14

M
Mikhail Osher, 2014-04-13
@miraage

What will the following code show you?
// upd fixed a bit

$input = [ /* your array */ ];
$fourteen = array_reverse(
    array_filter(
        $input,
        function($item) { return $item['COUNTER-ID'] == 14; }
    )
);
$needle = isset($fourteen[0]) ? $fourteen[0]['VALUE'] : null;

D
Dmitry Korshunov, 2014-04-13
@dkorshunov55

If COUNTER-ID is unique:

function arrRevers(Array &$input_array){
   $result = array();
   foreach($inputArray as $item)
      $result[$item['COUNTER-ID']] = $item;
   $input_array = $result;
}

Usage:
$array = array(/*массив*/);
arrRevers($array);
echo $array[14]['VALUE'];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question