I'm trying to make a list of Google Font choices to use in a dropdown in the WordPress Customizer but I am having difficulty getting this loop right:
$i = 0;
foreach ($items as $font_value => $item) {
$i++;
$str = $item['family'];
}
The string above need to be inside in the array below to generate a list of choices:
$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'ounox-fonts-display-control', array(
'label' => 'Fonts Section',
'section' => 'ounox-fonts-section',
'settings' => 'ounox-fonts-display',
'type' => 'select',
'choices' => $str
)));
The choices argument expects an array , and not a string, so you would need to save each $item['family'] into an array instead, and then add that array to the argument.
Hapstyx is also correct in pointing out that you don't need the $i++ to iterate your loop.
The array that choices expects for your drop down options should look something like this:
$choices = array(
'option-value-1' => 'Option Title 1',
'option-value-2' => 'Option Title 2',
'option-value-3' => 'Option Title 3'
);
We can build this type of array like this:
//predefine a blank array which we will fill with your options
$choices = array();
//loop through your items and that the values to the $choices array
foreach ($items as $font_value => $item) {
$choices[$item['slug']] = $item['family']; //I'm assuming your $item array contains some sort of slug to set as the value, otherwise, comment the above out, and uncomment the below:
// $choices[$item['family']] = $item['family']
}
//set your arguments
$args = array(
'label' => 'Fonts Section',
'section' => 'ounox-fonts-section',
'settings' => 'ounox-fonts-display',
'type' => 'select',
'choices' => $choices
);
//add the control
$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'ounox-fonts-display-control', $args));
A foreach loop doesn't need a counter so $i is redundant.
You're also overriding $str with each iteration.
$str = '';
foreach ($items as $font_value => $item) {
$str .= $item['family']; // . '##' in case you need a delimiter
}
Related
I have a problem where I am getting data from database and need to put that in an array. The array is associative and I am not sure about this practice so I thought I should ask the community. Is this the correct way of adding data to array? The array is for the radio buttons that will be provided to the helper class in prestashop. The array structure is important. This is the var_dump array structure which I have in $options_break2.
$options_value = array();
$options = array();
for($z=0; $z<sizeof($options_break2); $z++)
{
$options_value = array_push($options_value,
array(
"id" => $options_break2[$z],
"name" => $options_break2[$z],
"label" => $options_break2[$z],
)
);
}
$options = array_push($options, $options_value);
What I want is that the array should contain something like:
$example = array(
array(
'id_option' => 'some value',
'name' => 'some value',
),
array(
'id_option' => 'some value',
'name' => 'some value',
),
);
Actually you don't need to use array_push and array() if your PHP version is above 5.6, and you can improve your loop by using the foreach loop:
$options_value = [];
foreach ($options_break2 as $opt) {
$options_value[] = [
"id_option" => $opt, // some_value
"name" => $opt // some_value
];
}
$options = $options_value; // you don't really need this
I have this variable:
$families = array(
array(
'expand' => '',
'family_id' => 'AAER',
'active' => true,
'description' => 'Wall Art',
'group_id' => 5
),
array(
'expand' => '',
'family_id' => 'EERR',
'active' => true,
'description' => 'Personalised Mugs',
'group_id' => 4
),
);
And I want add to my $families items a field called 'href', like this:
$families = array(
array(
'href' => 'http://mipage/wall-art/AAER',
'expand' => '',
'family_id' => 'AAER',
'active' => true,
'description' => 'Wall Art',
'group_id' => 5
),
array(
'href' => 'http://mipage/personalised-mug/EEER',
'expand' => '',
'family_id' => 'EERR',
'active' => true,
'description' => 'Personalised Mugs',
'group_id' => 4
),
);
To do this I iterate $families in a foreach loop:
foreach($cat['families'] as $cat_fam) {
$cat['families'][]['href'] = 'http//mysite/'.str_slug($cat_fam).'/'.$cat_fam['family_id'];
}
But this not works for me.
How can I make this?
You've to repalce empty [] with the specific key. For this update foreach block to get key of the element and use that inside foreach loop.
$cat['families'][$key] which points to individual element of the families array.
Like this,
foreach($cat['families'] as $key=>$cat_fam) {
$cat['families'][$key]['href'] = 'http//mysite/'.str_slug($cat_fam).'/'.$cat_fam['family_id'];
}
Demo: https://eval.in/636898
just iterate over the array, and add a key ahref
$newArray= array();
foreach($families as $innerArray){
$innerArray['ahref']='YOUR LINK HERE';
$newArray[] = $innerArray;
}
$families = $newArray ;//if you want to update families array
Do something like:
$href = array('href'=>'http://mipage/wall-art/AAER');
$combined_array = array_combine($families[0],$href);
Don't tested but you can try or modify as per your use
Please try this:
I think you also forgot to add index description in your str_slug call.
foreach($cat['families'] as &$cat_fam) {
$cat_fam['href'] = 'http://mysite/'.str_slug($cat_fam['description']).'/'.$cat_fam['family_id'];
}
You can use the php function array_walk
Liek this :
array_walk($cat['families'], function(&$family){
$family['href'] = 'http//mysite/'.str_slug($family).'/'.$family['family_id'];
});
note the $family variable is passed by reference.
I have a multidimensional array and I need to count how many items are in each category:
array (
array(
'name' => 'Bob',
'category' => '2'
),
array(
'name' => 'Bill',
'category' => '6'
),
array(
'name' => 'John',
'category' => '1'
),
array(
'name' => 'Jack',
'category' => '2'
),
)
I want to be able to split these up into categories.
For example;
Category 2 contains 2 items
Category 1 contains 1 item
Category 6 contains 1 item
Just to get the count of each category would be great, but to be able to re-arrange the array into categories would also be useful. I'd like to be able to do both.
I've tried searching StackOverflow but I couldn't find this specific query. I'm guessing this may use array_map somewhere but I'm not good with that function.
Any help is greatly appreciated!
If your array isn't too big a straightforward approach might be the easiest one. Create a new array, use categories as keys and iterate over your array, counting items.
I have written 3 functions that solves the criteria you have described. Keep in mind these functions are bare minimum and lack error handling. It is also assumed the $categories array which all the functions requires has the structure outlined in your question.
The first rearranges all items into the correct category.
function rearrangeCategories(array $categories) {
$calculated = [];
foreach($categories as $category) {
$calculated[$category['category']][] = $category['name'];
}
return $calculated;
}
The second creates an associative array of the amount of items in each category. The array index is the category name/id and the value is an integer declaring the amount of items.
function categoriesCount(array $categories) {
$calculated = [];
$arranged = rearrangeCategories($categories);
foreach($arranged as $category => $values) {
$calculated[$category] = count($values);
}
return $calculated;
}
The third function checks how many items are stored inside a specific category. If the category doesn't exists FALSE is returned. Otherwise an integer is returned.
function categoriesItemCount(array $categories, $key) {
$arranged = rearrangeCategories($categories);
if(!array_key_exists($key, $arranged)) {
return false;
}
return count($arranged[$key]);
}
I hope this helps, happy coding.
You can use something like this
$arr =
array (
array(
'name' => 'Bob',
'category' => '2'
),
array(
'name' => 'Bill',
'category' => '6'
),
array(
'name' => 'John',
'category' => '1'
),
array(
'name' => 'Jack',
'category' => '2'
),
);
$categoryCount = array();
$categoryList = array();
array_map(function($a) use (&$categoryCount, &$categoryList) {
$categoryId = $a['category'];
if (!isset($categoryCount[$categoryId])) {
$categoryCount[$categoryId] = 0;
}
$categoryCount[$categoryId]++;
if (!isset($categoryList[$categoryId])) {
$categoryList[$categoryId] = array();
}
$categoryList[$categoryId][] = $a['name'];
}, $arr);
print_r($categoryCount);
print_r($categoryList);
This will create 2 arrays: one with the counts and one with the elements rearranged
Try this way, i think it will fulfill your requirements.
$arr=array (
array(
'name' => 'Bob',
'category' => '2'
),
array(
'name' => 'Bill',
'category' => '6'
),
array(
'name' => 'John',
'category' => '1'
),
array(
'name' => 'Jack',
'category' => '2'
),
);
$result = call_user_func_array('array_merge_recursive', $arr);
//for just show array
print '<pre>';
print_r(array_count_values($result['category']));
print '</pre>';
//loop as you need
foreach(array_count_values($result['category']) as $k=>$v){
$item=($v>1)? 'items':'item';
echo "Category ".$k." Contains " .$v." ".$item."<br/>";
}
Let's say I have an array formatted like so:
$data = array(
'variables' => array(
'823h9fhs9df38h4f8h' => array(
'name' => 'Foo',
'value' => 'green'
),
'sdfj93248fhfhf88rh' => array(
'name' => 'Bar',
'value' => 'red'
)
)
);
Say I wanted to access the name & values of each array in the variables array. Surely you can access it just looping over the main variables array and not looping over each individual item array? Something like so?
foreach ($data as $k => $v) {
$name = $data['variables'][0]['name'];
}
I'm sure I'm missing something simple...
You can do
foreach ($data['variables'] as $k => $v) {
$name = $v['name'];
}
You can also try this
create a new array containing just the names..
$new_arr = array_column($data['variables'],'name' );
echo $new_arr[0].'<br/>';
echo $new_arr[1].'<br/>';
In Wordpress I'm trying to create a metabox script from scratch to better understand both Wordpress and PHP.
I'm having some problems with a for each loop on a multidimensional array though. I'm using PHP5.
This is the array:
$meta_box = array();
$meta_box[] = array(
'id' => 'monitor-specs',
'title' => 'Monitor Specifications',
'context' => 'normal',
'priority' => 'default',
'pages' => array('monitors', 'products'),
'fields' => array(
array(
'name' => 'Brand',
'desc' => 'Enter the brand of the monitor.',
'id' => $prefix . 'monitor_brand',
'type' => 'text',
'std' => ''
)
)
);
And this is the for each loop:
foreach ($meta_box['pages'] as $post_type => $value) {
add_meta_box($value['id'], $value['title'], 'je_format_metabox', $post_type, $value['context'], $value['priority']);
}
What I'm trying to do is loop through the keys in the 'pages' array which is an array inside the 'meta_box' array and at the same time be able to use the key values of the 'meta_box' array.
Do I need to nest some for each loops?
Would be grateful for some pointers in the right direction so I can solve this.
foreach ($meta_box[0]['pages'] as $post_type => $value) {
or
$meta_box = array(...
Your foreach starts with $meta_box['pages'], but there is no $meta_box['pages'].
You do have a $meta_box[0]['pages'] though, so you need two loops:
foreach($meta_box as $i => $box)
foreach($box['pages'] as $page)
add_meta_box(.., ..); // do whatever
What were you expecting to be in your $value variable?
this here:
$meta_box = array();
$meta_box[] = array(......
suggests that there is no $meta_box['pages']. meta_box is an array with numerical indexes (check the [] operator) and each of its elements is an array that has the key 'pages'.
so you need to use foreach on $meta_box, and on each element you need to use the pages key.. id, title, context are elements on the same level as pages, as you can see
You are referencing to the wrong array key
$meta_box[] <-- $meta_box[0]
But, you refer using :-
foreach ($meta_box['pages'] as $post_type => $value) {
Add the array key will solve the problem :-
foreach ($meta_box[0]['pages'] as $post_type => $value) {
Maybe it could be nice to create some class to hold this information.
class Metabox
{
public $id, $title, $context, $priority, $pages, $fields;
public function __construct($id, $title, $pages, $fiels, $context='normal', $priority='default')
{
$this->id = $id;
$this->title = $title;
$this->pages = $pages;
$this->fields = $fields;
$this->context = $context;
$this->priority = $priority;
}
}
$meta_box = array();
$meta_box[] = new Metabox(
'monitor-specs',
'Monitor Specifications',
array('monitors', 'products'),
array(
'name' => 'Brand',
'desc' => 'Enter the brand of the monitor.',
'id' => $prefix . 'monitor_brand',
'type' => 'text',
'std' => ''
)
);
Now you can loop over the meta_box array like:
foreach ($meta_box as $box)
{
add_meta_box($box->id, $box->title, .. and more)
// This function could be placed in the metabox object
/* Say you want to access the pages array : */
$pages = $box->pages;
foreach ($pages as $page)
{
..
}
}
Now you still have a loop in a loop, but maybe helps seeing your problem more clearly.