Item position in an array - php

If I have id number and an array in the following format, how do I find out what count (position number) 'Red' among all other items where cat == 4? The answer I am looking for #3 of 4.
Array
(
[0] => stdClass Object
(
[id] => 1
[cat] => 1
[que] => Description here.
)
[1] => stdClass Object
(
[id] => 2
[cat] => 1
[que] => Description here.
)
[2] => stdClass Object
(
[id] => 3
[cat] => 1
[que] => Description here.
)
....
[31] => stdClass Object
(
[id] => 32
[cat] => 4
[que] => Description here.
)
[32] => stdClass Object
(
[id] => 33
[cat] => 4
[que] => Description here.
)
[33] => stdClass Object
(
[id] => 34
[cat] => 4
[que] => Red.
)
[34] => stdClass Object
(
[id] => 35
[cat] => 4
[que] => Description here.
)
)
Do I need to split array and then loop? Lost...
--------- EDIT ----------
OK, I did a bad job explaining...
What I meant was: there are many objects withing this array. They are broken into groups, categories. [cat] is the value for each group. There are multiple items in each group. What I was hoping to get was a number of items in each group and the position of particular item withing that group, for example: 4 out of 12.

$position = 0;
$counts = array();
foreach ($yourarray as $obj) {
if (!isset($counts[$obj->cat])) $counts[$obj->cat] = 0;
$counts[$obj->cat]++;
if ($obj->cat == 4 && $obj->que == "Red") {
$position = $counts[$obj->cat];
}
}
if ($position >= 0) {
echo "Object is $position out of $counts[4] objects in category 4\n";
}
foreach($counts as $key=>$val){
echo "Category $key has $val objects.\n";
}
(Revised to count all categories)

My edit to Ian Shannon's answer was rejected, so here's what I was proposing, which builds on his by using object notation instead of array notation and keeps track of the total.
I think the simplest way would be to loop through the array with a foreach, and if cat == 4, increment a counter until you reach the one you want. Something like this:
$pos = 0;
$total = 0;
foreach ($yourarray as $subarray) {
if ($subarray->cat == 4) {
$total++;
if ($subarray->que == "Red") {
$pos = $total;
}
}
}
$pos will be the position of the element you're looking for, and $total will be the total in that category.

$found = 0;
foreach ($array as $key => $value) {
if($value->cat == '4'){
$arrayPosition = $key;
$found++;
}
}
echo 'Found ' . $found . ' cat\'s, matching the criteria';
Didn't exactly understand what the matching criteria should be except for cat=4, and if "que" contains some more information you want to match, change the if statement.
if($value->cat == '4' && $value->que == 'Red'){

Related

select array value of an object in php

I'm just a beginner and would like to select a value of an array inside an object. I'm quite lost and don't know how to do.
ie : how to get de value of "thailande" inside this object ?
Forminator_Form_Entry_Model Object
(
[entry_id] => 42
[entry_type] => custom-forms
[form_id] => 24342
[is_spam] => 0
[date_created_sql] => 2020-07-02 11:42:21
[date_created] => 2 Juil 2020
[time_created] => 2 Juil 2020 # 11:42
[meta_data] => Array
(
[select-1] => Array
(
[id] => 87
[value] => thailande
)
[radio-1] => Array
(
[id] => 88
[value] => 1
)
[number-1] => Array
(
[id] => 89
[value] => 10
)
[_forminator_user_ip] => Array
(
[id] => 90
[value] => 84.101.156.169
)
)
[table_name:protected] => politis_5_frmt_form_entry
[table_meta_name:protected] => politis_5_frmt_form_entry_meta
)
thx a lot for your help.
It's fairly straightforward - you just go down the hierarchy one step at a time referencing the index you need.
So, assuming $obj in this example is an instance of Forminator_Form_Entry_Model then you would write
$obj->meta_data["select-1"]["value"]
which will point to the data you're looking for.
N.B. The ->index syntax is used to get properties of an object. the ["index"] syntax is used to get properties of an array.
You can try Callback Functions
function array_search_id($val_for_search, $array_data, $search_in_path='root') {
if(is_array($array_data) && count($array_data) > 0) { // if value has child
foreach($array_data as $key => $value) {
$paths_list = $search_in_path;
// Adding current key to search path
array_push($paths_list, $key);
if(is_array($value) && count($value) > 0) { // if value has child
$res = array_search_id($val_for_search, $value, $paths_list);//callback function
if ($res != null)
return $res;
}
else if($value == $val_for_search){
//if you wants path + result
return end($paths_list);
/*
//if you wants path
return join(" --> ", $paths_list);
*/
} //if value find in array return val
}
}
return null;
}
array_search_id('thailande', $your_array);

Face problem during get unique value from foreach loop

I have faced a problem during get unique value in foreach loop.
Following is my array.
Array
(
[20] => Array
(
[0] => Array
(
[id] => 4
[category_title] => Specialist Range
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:17
)
[1] => Array
(
[id] => 4
[category_title] => Specialist Range
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:17
)
[2] => Array
(
[id] => 4
[category_title] => Specialist Range
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:17
)
[3] => Array
(
[id] => 6
[category_title] => Cater Foil Rolls
[parent] => 20
[front_active] => 1
[category_date] => 2019-05-21 04:04:24
)
)
[21] => Array
(
[8] => Array
(
[id] => 24
[category_title] => Specialist Range
[parent] => 21
[front_active] => 1
[category_date] => 2019-05-21 04:07:59
)
[9] => Array
(
[id] => 24
[category_title] => Specialist Range
[parent] => 21
[front_active] => 1
[category_date] => 2019-05-21 04:07:59
)
)
)
I written following script for getting unique value in loop
$catArray = array();
foreach($catagory_list as $key=>$catagory){
$catArray[$catagory['parent']][$key] = $catagory;
}
ksort($catArray, SORT_NUMERIC);
foreach ($catArray as $key => $value) {
if($key == 20 ){
$catName ='local';
}elseif ($key == 21) {
$catName ='interstate';
}elseif ($key == 22) {
$catName ='wholesale';
}elseif ($key == 23) {
$catName ='tst';
}
//echo $key;
foreach(array_unique($value) as $keys => $valuess){
echo $valuess['category_title'];
?>
<tr class="table_header">
<th><?php echo $catName." - ".$valuess['category_title'];?> </th>
</tr>
<?php
}
}
Problem is 20 has 4 category_title but when i used array_unique Cater Foil Rolls category title of first parent array is not display.
Output only display
Specialist Range not showing (Cater Foil Rolls)
If you are trying to find unique records in this nested array, then I would key your associative array off of the value of "id". If you are only trying to find unique category_title, then I would key off the value of "category_title". In any case I would use the associate array functionality to ensure uniqueness on whatever key you choose. Then you can apply sorting, etc. on the result.
// find first unique records
$result = [];
foreach($parents as $key1=>$child1) {
foreach($child1 as $key2=>$child2) {
if(!isset($result[$child2['id']])) {
$result[$child2['id']] = $child2;
}
}
}
// result = # => record
OR:
// find first unique categories
$result = [];
foreach($parents as $key1=>$child1) {
foreach($child1 as $key2=>$child2) {
if(!isset($result[$child2['category_title']])) {
$result[$child2['category_title']] = $child2;
}
}
}
// result = category => record
I'm not convinced that array_unique works on multi-dimensional arrays.
See this question.

PHP: Update objects array values with another unsorted objects array

I have two objects arrays.
First array $x:
[0] => stdClass Object
(
[id] => 54
[value] => test54
[something] => testtest54
)
[1] => stdClass Object
(
[id] => 21
[value] => test21
[something] => testtest21
)
...
Second array $y:
[0] => stdClass Object
(
[id] => 21
[value] => test21_new_value
)
[1] => stdClass Object
(
[id] => 54
[value] => test54_new_value
)
...
I want to update my first array $x importing value of the second array's ($y) field which has the same id, I want to have :
[0] => stdClass Object
(
[id] => 54
[value] => test54_new_value
[something] => testtest54
)
[1] => stdClass Object
(
[id] => 21
[value] => test21_new_value
[something] => testtest21
)
...
I can do something like this :
foreach($x as $k => $v) {
foreach($y as $k2 => $v2) {
if ($v->id === $v2->id) $x[$k]->value = $v2->value;
}
}
But I don't like this, because I have to walk on array $y for each $x (if I have 100 items in $x and 100 items in $y, it loops 100*100 times). I think there is a more efficient, elegant or optimized way to do this, but I don't know how to do that (I did not found a precise response to this specific problem, so I ask here).
Sure. Usually you'd use an associative array for this (with the key being the unique ID), as this would mean (100 + 100) iterations instead of (100 * 100):
<?php
$assocX = array();
foreach ($x as $v) {
$assocX[$v->id] = $v;
}
foreach ($y as $v) {
$v->something = $assocX[$v->id]->something;
}
?>
If you can't be sure that the value exists in $x you can also check for this ("no value" would be translated to NULL):
<?php
$assocX = array();
foreach ($x as $v) {
$assocX[$v->id] = $v;
}
foreach ($y as $v) {
$v->something = (isset($assocX[$v->id]) ? $assocX[$v->id]->something : null);
}
?>

Checking if array value exists in a PHP multidimensional array

I have the following multidimensional array:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
I'm currently using a foreach loop to extract the values from the array:
foreach ($result as $key => $sub)
{
...
}
But I was wondering how do I see whether a value within the array already exists.
So for example if I wanted to add another set to the array, but the id is 1 (so the person is Jonah) and their score is 5, can I add the 5 to the already created array value in id 0 instead of creating a new array value?
So after the loop has finished the array will look like this:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 32 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
What about looping over your array, checking for each item if it's id is the one you're looking for ?
$found = false;
foreach ($your_array as $key => $data) {
if ($data['id'] == $the_id_youre_lloking_for) {
// The item has been found => add the new points to the existing ones
$data['points'] += $the_number_of_points;
$found = true;
break; // no need to loop anymore, as we have found the item => exit the loop
}
}
if ($found === false) {
// The id you were looking for has not been found,
// which means the corresponding item is not already present in your array
// => Add a new item to the array
}
you can first store the array with index equal to the id.
for example :
$arr =Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
);
$new = array();
foreach($arr as $value){
$new[$value['id']] = $value;
}
//So now you can check the array $new for if the key exists already
if(array_key_exists(1, $new)){
$new[1]['points'] = 32;
}
Even though the question is answered, I wanted to post my answer. Might come handy to future viewers. You can create new array from this array with filter then from there you can check if value exist on that array or not. You can follow below code. Sample
$arr = array(
0 =>array(
"id"=> 1,
"name"=> "Bangladesh",
"action"=> "27"
),
1 =>array(
"id"=> 2,
"name"=> "Entertainment",
"action"=> "34"
)
);
$new = array();
foreach($arr as $value){
$new[$value['id']] = $value;
}
if(array_key_exists(1, $new)){
echo $new[1]['id'];
}
else {
echo "aaa";
}
//print_r($new);

Find & track max value in a multidimensial array

I have a multidimensional array that looks like this:
Array
(
[0] => Array
(
[id] => 2280764150
[label] => Some Label A
[pda] => 5.34
[prt] => 67
[kps] => 12436
[xmv] => 1.24
)
[1] => Array
(
[id] => 2273499083
[label] => Some Label B
[pda] => 2.99
[prt] => 97
[kps] => 212436
[xmv] => 7.78
)
[2] => Array
(
[id] => 2273045947
[label] => Some Label C
[pda] => 6.34
[prt] => 157
[kps] => 1436
[xmv] => 2.34
)
)
What I would like to do is find out which array element has the max value for each of items pda prt kps and xmv. It's not so much I want to know what the max value is, but I want to know which one has the max elements for each. So Some Label C would be logged as having max pda, Some Label B having max value for kps and so on.
I could do this with a few loops, but was looking for a more elegant solution.
Here's another one. I'm not sure if it's elegant, though.
$arr = array(
array('id'=>2280764150,'label'=>'Some Label A','pda'=>5.34,'prt'=>67,'kps'=>12436,'xmv'=>1.24),
array('id'=>2273499083,'label'=>'Some Label B','pda'=>2.99,'prt'=>97,'kps'=>212436,'xmv'=>7.78),
array('id'=>2273045947,'label'=>'Some Label C','pda'=>6.34,'prt'=>157,'kps'=>1436,'xmv'=>2.34),
);
$max = array('pda'=>0,'prt'=>0,'kps'=>0);
foreach (array_keys($max) as $key) {
array_walk($arr,'get_max',$key);
}
function get_max($inner_arr,$index,$key) {
global $max;
if ($inner_arr[$key] > $max[$key]['max'])
$max[$key] = array('index'=>$index,'max'=>$inner_arr[$key]);
}
print_r($max);
EDIT: ABOVE CODE SHORTENED
$max = array('pda'=>0,'prt'=>0,'kps'=>0);
array_walk($arr,'get_max');
function get_max($inner_arr,$index) {
global $max;
foreach (array_keys($max) as $key) {
if ($inner_arr[$key] > $max[$key]['max'])
$max[$key] = array('index'=>$index,'max'=>$inner_arr[$key]);
}
}
This is the most elegant solution I can think of:
$max=Array();
foreach ($yourArray as $key=>$nestedArray) {
foreach ($nestedArray as $item => $val) {
if (!isset($max[$item]) || $max[$item]['val']<$val) {
$max[$item]['val']=$val;
$max[$item]['key']=$key;
}
}
}

Categories