PHP - Add multiple items by index to multidimensional array - php

I have this array called $all_cats which outputs the following
Array(
[0] => WP_Term Object(
[term_id] => 386
[name] => Ales
[slug] => ales
[term_group] => 0
[term_taxonomy_id] => 386
[taxonomy] => product_cat
[description] =>
[parent] => 384
[count] => 10
[filter] => raw
)
[1] => WP_Term Object(
[term_id] => 385
[name] => Beers
[slug] => beers
[term_group] => 0
[term_taxonomy_id] => 385
[taxonomy] => product_cat
[description] =>
[parent] => 384
[count] => 10
[filter] => raw
)
)
I'm trying to add the "term_id" and "name" to an indexed multidimensional array so i can output the following -
Example A
Array
(
[0] => Array
(
[parent_cats] => Array
(
[id] => 385,
[name] => "Beers"
)
)
[1] => Array
(
[parent_cats] => Array
(
[id] => 386,
[name] => "Ales"
)
)
)
I've tried the following but cant seem to add each item to the same key. How can i add each term_id & name so it outputs like example A?
$full_cats = array();
foreach ($all_cats as $cat_term) {
$parent_termID = $cat_term->term_id;
$parent_title = $cat_term->name;
// this doesnt work
$full_cats[]['parent_cats']['id'] = $parent_termID;
$full_cats[]['parent_cats']['name'] = $parent_title;
// this doesnt work
array_push($full_cats[]['parent_cats']['id'],$parent_termID);
array_push($full_cats[]['parent_cats']['name'],$parent_title);
}
How can i add each term_id & name so it outputs like example A?

$full_cats = array();
foreach ($all_cats as $cat_term) {
$parent_termID = $cat_term->term_id;
$parent_title = $cat_term->name;
// this doesnt work
$full_cats[]=array(
"parent_cats"=>array(
"id" => $parent_termID,
"name" => $parent_title
)
);
}
The above code should work
You need to learn the structure of multi and assoc array

$full_cats = array();
$indx = 0;
foreach ($all_cats as $cat_term) {
$parent_termID = $cat_term->term_id;
$parent_title = $cat_term->name;
// this doesnt work
$full_cats[$indx]['parent_cats']['id'] = $parent_termID;
$full_cats[$indx]['parent_cats']['name'] = $parent_title;
$indx++;
// this doesnt work
// array_push($full_cats[]['parent_cats']['id'],$parent_termID);
// array_push($full_cats[]['parent_cats']['name'],$parent_title);
}

Related

Creating an array with specific keys and strings into one array

I created a function that gets the product_id and its category_id where the product_id = the product_id supplied like so:
public function getCategorys($product_id){
$sql = "SELECT category_id,product_id FROM oc_product_to_category WHERE product_id = '$product_id'";
$result = $this->query($sql);
$categories = $this->getResult($result);
return $categories;
}
This is function is called with the following code:
foreach($product_ids as $product_id){
$categories[] = $data->getCategorys($product_id);
}
I then create an array containing the product_id and each category_id that product is found in, I did this with the following code:
$product_categories = array();
foreach($categories as $category){
foreach($category as $cat){
if($cat['product_id'])
$product_categories[] = array(
'product_id' => $cat['product_id'],
'category_id' => $cat['category_id']
);
}
}
Now when I print_r($product_categories) I get the following result (this is just part of it I wont put the full array in because its large):
Array
(
[0] => Array
(
[product_id] => 9319
[category_id] => 293
)
[1] => Array
(
[product_id] => 9319
[category_id] => 313
)
[2] => Array
(
[product_id] => 11969
[category_id] => 395
)
[3] => Array
(
[product_id] => 11969
[category_id] => 396
)
Now what I'm trying to achieve is: I want an array that has the product ID and each category_id that it is found in so for example the first two arrays with product id 9319 and 11969 I would want that to look like this:
[0] => Array
(
[product_id] => 9319
[category_id] => 293,313
)
[1] => Array
(
[product_id] => 11969
[category_id] => 395,396
)
I know this isn't articulated very well but I'm not sure how else to phrase this question! I essentially want all the duplicate product id's removed and all their category_id's as one comma separated string in the same array.
EDIT:
I tried the answer provided Group array by subarray values
However I'm getting this output instead now:
Array
(
[22] => Array
(
[133] => Array
(
[product_id] => 22
[category_id] => 313
)
)
[59] => Array
(
[320] => Array
(
[product_id] => 59
[category_id] => 294
)
[321] => Array
(
[product_id] => 59
[category_id] => 331
)
)
[63] => Array
(
[368] => Array
(
[product_id] => 63
[category_id] => 292
)
[369] => Array
(
[product_id] => 63
[category_id] => 302
)
)
[87] => Array
(
[51] => Array
(
[product_id] => 87
[category_id] => 293
)
[52] => Array
(
[product_id] => 87
[category_id] => 313
)
)
This is nearly close to what I want but I want all the category ids in array for that product_id.
Would you not be better off with an array that has the product_id as the key which contained an array of category_id's Comma delimited lists mark the entry point to the road to hell
Make you foreach loop do this instead
$product_categories = [];
foreach($categories as $cat){
$product_categories[$cat['product_id']][] = $cat['category_id'];
}

Removing parts of a multidimensional array that do not have a key that matches a separate array?

I have an array that is full of IDs that will match corresponding IDs in a separate array which is larger in terms of indices. I would like to first search through the larger array using the IDs from the smaller array and eliminate any indices that do not appear in the smaller array, and then place values present in the arrays that do match in my initial, smaller array. I have tried various nested for loops (come close, but does not get me there) but I can't seem to wrap my head about some array problems in general.
First array will look something like this:
Array
(
[0] => Array
(
[roleID] => 5b6468a500277c71b98405b1f140991c
[name] =>
[description] =>
[rate] =>
[hours] =>
[total] =>
)
[1] => Array
(
[roleID] => 5b6468a500277c74f6b2c065436b7d17
[name] =>
[description] =>
[rate] =>
[hours] =>
[total] =>
)
[2] => Array
(
[roleID] => 5b6468a500277c7697ba21928129e3af
[name] =>
[description] =>
[rate] =>
[hours] =>
[total] =>
)
)
Second array will look something like this
Array
(
[0] => stdClass Object
(
[ID] => 5b6468a500277c71b98405b1f140991c
[name] => CED
[objCode] => ROLE
[description] => CED
)
[1] => stdClass Object
(
[ID] => 5b6468a500277c74f6b2c065436b7d17
[name] => AD
[objCode] => ROLE
[description] => AD
)
[2] => stdClass Object
(
[ID] => 5b6468a500277c7697ba21928129e3af
[name] => AMG
[objCode] => ROLE
[description] => AMG
)
[3] => stdClass Object
(
[ID] => 5b6468a500277c77071c32c0bb2bae04
[name] => AP
[objCode] => ROLE
[description] => AP
)
[4] => stdClass Object
(
[ID] => 5b6468a500277c787e9680625c74ca80
[name] => AST
[objCode] => ROLE
[description] => AST
)
[5] => stdClass Object
(
[ID] => 5b6468a500277c79c0eddb8c14cc9f83
[name] => ASV
[objCode] => ROLE
[description] => ASV
)
)
I want to match the roleID in the first ID with the ID in the second array, then take the 'name' and 'description' keys and put it in the first array in the position it belongs. I have gotten close with the below code, but either a bunch of the arrays get misordered, or the 'name' and 'description' fields are the exact same for every index.
$projectUserRoleIDs = $client->get('project', $myProjectName, array('projectUserRoles:roleID'));
$projectUserRoleIDs = $projectUserRoleIDs->projectUserRoles;
$roleIDs = [];
for($a = 0; $a < count($projectUserRoleIDs); $a++)
{
$roleIDs[$a]['roleID'] = $projectUserRoleIDs[$a]->roleID;
// Get array of entire list of roles that are available in Workfront
// The roles:name category has all of the acronyms for each role, which can appear in an invoice
// The roles:description category has all of the full length names
$projectRoles = $client->get('project', $myProjectName, array('roles:name', 'roles:description'));
$projectRoles = $projectRoles->roles;
$roleLoop = [];
for($b = 0; $b < count($projectUserRoleIDs); $b++)
{
$roleLoop[] = $projectUserRoleIDs[$b]->roleID;
}
foreach($roleLoop as $key => $value) {
for($x = 0; $x<count($projectRoles); $x++)
{
if($projectRoles[$x]->ID === $value)
{
$name = $projectRoles[$x]->name;
$description = $projectRoles[$x]->description;
$roleIDs[$x]['name'] = $name;
$roleIDs[$x]['description'] = $description;
}
}
}
$roleIDs[$a]['rate'] = '';
$roleIDs[$a]['hours'] = '';
$roleIDs[$a]['total'] = '';
}
In the end I want my first array to look like this
Array
(
[0] => Array
(
[roleID] => 5b6468a500277c71b98405b1f140991c
[name] => CED
[description] => CED
[rate] =>
[hours] =>
[total] =>
)
[1] => Array
(
[roleID] => 5b6468a500277c74f6b2c065436b7d17
[name] => AD
[description] => AD
[rate] =>
[hours] =>
[total] =>
)
And so on... any help is appreciated and thank you.

Create simple array from complex array

I have the following two arrays:
Array One
Array ( [0] => WP_Term Object ( [term_id] => 36 [name] => Fractions [slug] => fractions-cat [term_group] => 0 [term_taxonomy_id] => 36 [taxonomy] => emp_unit_name [description] => [parent] => 0 [count] => 11 [filter] => raw [term_order] => 0 )
[1] => WP_Term Object ( [term_id] => 38 [name] => Geometry [slug] => geometry [term_group] => 0 [term_taxonomy_id] => 38 [taxonomy] => emp_unit_name [description] => [parent] => 0 [count] => 2 [filter] => raw [term_order] => 0 )
)
Array Two
Array ( [0] => WP_Term Object ( [term_id] => 36 [name] => Fractions [slug] => fractions-cat [term_group] => 0 [term_taxonomy_id] => 36 [taxonomy] => emp_unit_name [description] => [parent] => 0 [count] => 11 [filter] => raw [term_order] => 0 ) )
I'm trying to compare the two arrays to find if there are any matches for the [term_id] values as such:
$match = array_intersect($array_one_ids, $array_two_ids);
if( count($match) > 0) { echo 'we have a match!'; }
My question is, how can I create arrays (defined by $array_one_ids and $array_two_ids) of just the term_id values in each of the above arrays such that $array_one_ids would = array(36, 38) and $array_two_ids would = array(36)?
You can use array_column on each of the input arrays to convert them to arrays of term_id.
$match = array_intersect(
array_column($arrayOne, 'term_id'),
array_column($arrayTwo, 'term_id')
);
For older PHP versions where array_column doesn't handle arrays of objects, you can use array_map to extract that property.
$match = array_intersect(
array_map(function($term) { return $term->term_id; }, $arrayOne),
array_map(function($term) { return $term->term_id; }, $arrayTwo)
);
Also, you don't have to count $match to check the result, as an array evaluates to true or false in an if condition depending on whether it's empty. (See "converting to boolean".)
if ($match) { echo 'we have a match!'; }
If you do not need the whole WP_Term object, you can add a fields parameter to your query when you retrieve it to only retrieve the ids of the terms.
For example:
$queryOne = new WP_Term_Query(array(
'taxonomy' => 'emp_unit_name',
... // The other args of your query,
'fields' => 'ids'
));
Then you can access the ids ($query->terms):
array(36, 38);
Once you have both queries, you could do:
$match = array_intersect($queryOne->terms, $queryTwo->terms);
However, if you need the whole object, you can do it like #Don't Panic's answer.

fastest way to get array block based on value contained within the block (not working)

https://gist.github.com/jcranny/9465715
I have this array (example)...
Array
(
[0] => Array
(
[series] => stdClass Object
(
[term_id] => 5
[name] => Moto2 2013
[slug] => moto2-2013
[term_group] => 0
[term_taxonomy_id] => 3
)
[race_number] => 77
[team] => Technomah carXpert
[constructor] => Suter
[machine] => Honda CBR600RR
)
[1] => Array
(
[series] => stdClass Object
(
[term_id] => 6
[name] => Moto2 2014
[slug] => moto2-2014
[term_group] => 0
[term_taxonomy_id] => 3
)
[race_number] => 15
[team] => La Fonte Tascaracing
[constructor] => Suter
[machine] => Honda CBR600RR
)
[2] => Array
(
[series] => stdClass Object
(
[term_id] => 7
[name] => Moto2 2015
[slug] => moto2-2015
[term_group] => 0
[term_taxonomy_id] => 3
)
[race_number] => 15
[team] => Mapfre Aspar Team Moto2
[constructor] => Suter
[machine] => Honda CBR600RR
)
)
Now I would like to be able to get information from each block.
For example I would like to echo this data:
[race_number]
[team]
[constructor]
[machine]
But I want only to echo this data that is relevant to a specific [series]
I have the [series] term_id so this is my key to get the relevant data, but i'm struggling to get my node function work.
This is the function to do this:
function node_modify_riders_array($rider_id)
{
$fields = get_field("rider_series_data", $rider_id);
foreach($fields as $field_key => $field_val)
{
$new_fields[$field_val["series"]] = $field_val;
}
return $new_fields;
}
Then this is how I am get the series specific data based on the series term id.
$rider_series_data = node_modify_riders_array($rider_id);
$series_id = $series[0]->term_id;
$team = $rider_series_data[$series_id]["team"];
$contstructor = $rider_series_data[$series_id]["constructor"];
$machine = $rider_series_data[$series_id]["machine"];
$race_number = $rider_series_data[$series_id]["race_number"];
But some thing is wrong and I can work it out. Can anyone see where I'm going wrong or help me fix it.
Massive thanks in advance, would really appreciate some help.
What the problem is:
My function node_modify_riders_array is returning null, which is causing my $team, $contstructor, $machine, and $race_number too not output anything.
If I echo $series_id on my example, I get 6
Which should pass though my node_modify_riders_array function and display the relevant array values. But it's not outputting anything and I got no errors.
This is my full code so you can see what I am trying to do...
https://gist.github.com/jcranny/9465715
You are using an object as your array key and not the term_id of your series object.
function node_modify_riders_array($rider_id)
{
$fields = get_field("rider_series_data", $rider_id);
foreach($fields as $field_key => $field_val)
{
$new_fields[$field_val["series"]->term_id] = $field_val;
//^^^^^^^^^ <--- add this
}
return $new_fields;
}

Comparing two stdClass Objects

I'm currently working on a modified search within a Wordpress theme that queries a custom taxonomy location and displays it's terms as search results. I couldn't find a built in Wordpress function to handle this, so I used a $wpdb query
$keywords = $_GET['s'];
$results = $wpdb->get_results( "SELECT * FROM $wpdb->terms WHERE name LIKE '%%$keywords%%'");
<ul>
<?php foreach ( $results as $result ) :?>
<li><?php echo $result->name;?></li>
<?php endforeach;?>
</ul>
The issue with this is the table wp_terms not only stores custom taxonomy terms, but other default terms as well. So in order to display search results just for the the custom taxonomy, not other default terms, I thought of using get_terms to get all of the terms belonging to the custom taxonomy location and display terms from the table wp_terms based off of get_terms result with in_array
$keywords = $_GET['s'];
$results = $wpdb->get_results( "SELECT * FROM $wpdb->terms WHERE name LIKE '%%$keywords%%'");
$terms = get_terms("location");
<ul>
<?php foreach ( $results as $result ) :?>
if(in_array($result->name, $terms)) :?>
<li><?php echo $result->name;?></li>
<?php endif;?>
<?php endforeach;?>
</ul>
However, $results and $terms are both stdClass Objects, so in_array doesn't work.
Is there either a function, method or possibly a MySQL query that will allow me to display results from the object $results based off the contents of the object $terms?
Thanks in advance.
EDIT:
Contents of $terms
Array (
[0] => stdClass Object ( [term_id] => 32 [name] => US [slug] => us [term_group] => 0 [term_taxonomy_id] => 32 [taxonomy] => signs [description] => [parent] => 25 [count] => 1 )
[1] => stdClass Object ( [term_id] => 22 [name] => EU [slug] => eu [term_group] => 0 [term_taxonomy_id] => 22 [taxonomy] => signs [description] => [parent] => 0 [count] => 3 )
[2] => stdClass Object ( [term_id] => 26 [name] => AU [slug] => au [term_group] => 0 [term_taxonomy_id] => 26 [taxonomy] => signs [description] => [parent] => 22 [count] => 1 )
[3] => stdClass Object ( [term_id] => 27 [name] => IE [slug] => ie [term_group] => 0 [term_taxonomy_id] => 27 [taxonomy] => signs [description] => [parent] => 22 [count] => 2 )
[4] => stdClass Object ( [term_id] => 23 [name] => PK [slug] => pk [term_group] => 0 [term_taxonomy_id] => 23 [taxonomy] => signs [description] => [parent] => 0 [count] => 2 )
)
You can convert them into arrays with
(array) $variable;
Or, if your stdClass contains nested stdClasses, you can do the following:
function obj_to_array_recursive(stdClass $obj) {
foreach ($obj as &$element) {
if ($element instanceof stdClass) {
obj_to_array_recursive($element);
$element = (array)$element;
}
}
$obj = (array)$obj;
return $obj;
}

Categories