Answer the question
In order to leave comments, you need to log in
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
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
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
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;
If COUNTER-ID is unique:
function arrRevers(Array &$input_array){
$result = array();
foreach($inputArray as $item)
$result[$item['COUNTER-ID']] = $item;
$input_array = $result;
}
$array = array(/*массив*/);
arrRevers($array);
echo $array[14]['VALUE'];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question