I want to use if for this array :
$options[] = array( "name" => __('slider Settings','wordpresstools'),
"desc" => __('','wordpresstools'),
"id" => $shortname."_favSlider",
"std" => "",
"type" => "select",
"options" => array(
'option1' => 'test',
'option2' => 'test 2',
'option3' => 'test 3'
));
if this select option = option1
echo " Test ";
I have more $options , but I want to if just for that option ( Slider Settings )
Thanks .
Maybe the problem in your code are those brackets after $options. That way you append a new array element to the collection which means you have to test for something like this:
// Assuming your code creates the first array element
if ($options[0]['std'] == 'option1') {
// Do your stuff
}
If you don't need the square brackets in your first line of code it would look like this:
$options = array(/* Your values */);
if ($options['std'] == 'option1') {
// Do your stuff
}
$shortname='test';
$options = array( "name" => create_function('slider Settings','wordpresstools'),
"desc" => create_function('','wordpresstools'),
"id" => $shortname."_favSlider",
"std" => " I am here",
"type" => "select",
"options" => array(
'option1' => 'test',
'option2' => 'test 2',
'option3' => 'test 3'
));
echo "<pre>";
print_r($options['std']);
If i am right you try to create a constructor function there. In order to do something like that you must use create function. Read more details here The output of this code is printing std field as you want. The downside is that this method will be deprecated in PHP 7.2 so maybe you can find another work around than creating functions inside an array.
Foreach loop on options
foreach($options['options'] as $k=>$v){
// Check value of key
if($k == 'option1'){
echo $v . "\n";
}
}
I'm not exactly sure what kind of implementation you need but this should be a decent start for however you're trying to use it. I'm not sure if you mean to always have option1, option2, option3, etc. set or if you're checking to see if they exist. If the prior, then you'd need to make a few slight changes; if the latter, then this should work fine as it will check every key value and it should only exist if the option is selected.
Related
In laravel, I have a working code block where I loop an array and within it I call an email list. However, there are certain elements in the array that have a specific email that I want to add to it. So I always want the existing email config list to be used no matter what, but if the array element of the person has an email key I want to add that to the emails array, if that makes sense.
Here is the existing code as it:
$items = array(
array(
"employee" => 123,
"name" => "Tom",
"email" => "Tom#sitepoint.com"
),
array(
"employee" => 234,
"name" => "Sally"
),
array(
"employee" => 345,
"name" => "Rob"
),
array(
"employee" => 456,
"name" => "Ed"
"email" => "ed#sitepoint.com"
),
array(
"employee" => 567,
"name" => "Barbara"
)
);
foreach($items as $item){
//if there is an override email in the command
if($this->option('email') != 'default') {
if(!filter_var($this->option('email'), FILTER_VALIDATE_EMAIL)) {
$this->error('invalid email:'.$this->option('email'));
return;
}
$emails = ['to'=>[$this->option('email')],'cc'=>[]];
} else {
//This line works as is but I want a condition so that if the array element has and "email" key, I add that value as well
$emails = config('emails.printouts.employeePrintOuts');
//here I would need to add the array value (if email is set in that element)
}
...
}
The part in question is only in the 'else' block. How can I properly do this so that only certain array elements will have an email key and if they do I add it to the emails array that is always using the config list?
As mentioned in comments, you can use array_key_exist() function to check that $items contain email key.
Also to fullfil $emails['to'] subarray only in case that it doesn't contain current $items['email'] you may use in_array() function.
Solution:
if ( array_key_exist('email', $item) && !in_array($item['email'], $emails['to']) )
{
//TODO validate $item['email'] here
$emails['to'][] = $item['email'];
}
//Result $emails array will be looks like this:
[
'to' => [ "Tom#sitepoint.com", "ed#sitepoint.com" ],
'cc' => []
]
I would like to output a JSON string with an optional fields.
Right now I do it as simple as:
echo json_encode(array(
'qwe' => 1,
'asd' => 2,
'zxc' => 3
));
Now, say, I would like to include/exclude the 'asd' element based on some logic (using an inline if or some function or something else).
I have no idea how to do it, because, AFAIK, there is no such type in PHP that can force json_encode to skip this field - everything returns null or empty fields but does not skip the field itself.
Any ideas someone?
do you mean something like this:
$arr = array(
array(
'qwe' => 1,
'asd' => 2,
'zxc' => 3
),
array(
'qwe' => 4,
'asd' => '',
'zxc' => 6
)
);
foreach ($arr as $key => $row) {
if ($row['asd'] == '') {
unset($arr[$key]['asd']);
}
}
echo json_encode($arr);
Short: Is there a way to get a named key/value from SUBARRAY without knowing the main key ?
Long:
Ive got a foreach loop that extracts text-files & turns them into individual / single arrays (resetting the array between each file)...
example:
Array
(
[Blah Blah] => Array
(
[number] => 10
[name] => nameBlah
[image] =>
)
)
Array
(
[pinkblue597] => Array
(
[number] => 18
[name] => nameBlah68
[image] =>
)
)
(the 1st part to turn into array is used by multiple parts of a process so I dont want to add unnecessary code)
I want to extract the value of "name" and "number", however I do not know the value / format of the key in advance.. - Example: pinkblue597
If I do print_r, I do see the array as I want...
print_r($found,true)."\n";
but if I do this, $name=$found[0]; I get no results for "$name"...
or
if I do this, $name=$found[0]["name"]; I get no results for "$name"...
I could do this via a foreach loop, but it seems inefficient...
PS there will only be ONE (unknown) key in this array, & a sub-array. The sub array is always the same.
Edited: made the code easier to see (forgot to do this)
If the array formation is going to be the same all the time...
then a (nested) foreach loop will suffice, take the example below,
<?php
$a = [
'somethingUnknown13582563' => [
'name' => 'name',
'number' => 15
],
'somethingUnknown2' => [
'name' => 'another name',
'number' => 24
]
];
foreach ($a as $key => $subArray) {
foreach ($subArray as $subKey => $value) {
echo $subArray[$subKey] . '<br>';
}
}
?>
Output
name
15
another name
24
Or...
You could use array_values,
<?php
$a = [
'somethingUnknown13582563' => [
'name' => 'first name',
'number' => 15
],
'somethingUnknown2' => [
'name' => 'name',
'number' => 24
]
];
$a = array_values($a);
echo $a[0]['name'];
?>
Which would turn the first associative array in to numeric indexes and would like so,
array(
0 => array(
'name' => 'first name',
'number' => 15,
),
1 => array(
'name' => 'name',
'number' => 24,
)
)
I'm not sure why you're creating a nested array in the first place if you only intend to discard it immediately, but since the array only appears to have a single element, and you only care about that element, you can simple use array_pop
$a = [
'somethingUnknown13582563' => [
'name' => 'first name',
'number' => 15
],
];
$data = array_pop($a);
echo $data['name']; // gives you 'first name'
Note that array_pop is destructive. So if you don't want this behavior you could use something like end instead.
$data = end($a); // same effect as array_pop but non-destructive
echo $data['name']; // also gives you 'first name'
With that said, the foreach construct isn't necessarily inefficient. I believe your true concern is around finding a simpler way to dereference the nested array. The easiest way to do that in your case is going to be using something like end($a)['name'] which gives you the kind of straight-forward dereferencing you're looking for.
You can use array_map() to achieve this...
array_map — Applies the callback to the elements of the given arrays. This will loop all the array elements through callback function and you can print each element present in the sub array..
<?php
$myArry = array(
'Blah Blah' => array(
'number' => 10,
'name' => 'Blah Blah 1',
),
'pinkblue597' => array(
'number' => 15,
'name' => 'Blah Blah 2',
)
);
array_map(function($arr){
echo 'Name : '.$arr['name'].'<br>';
echo 'Number : '.$arr['number'].'<br>';
},$myArry);
?>
This will give you :
Name : Blah Blah 1
Number : 10
Name : Blah Blah 2
Number : 15
So I have two array, the first one is like:
$MyArray = [
['id' => 1, number => 32],
['id' => 2, number => 4]
];
and the other is like:
$OtherArray = [
['id' => 1, 'show' => X],
['id' => 5, 'show' => X]
];
Where is X, I want it to be equal with the 'number' value of $MyArray where key 'id' = its id.
If there is no $MyArray.id which is equal to $OtherArray.id then it should return 0.
I hope you understand what I mean. I tried everything, what I could, yet, with no success.
Have you tried using a foreach loop here?
Here is a quick example... PHPaste Snippet
<?php
$firstArray = array(
array(
"id" => 1,
"something" => "Hello, World!"
),
array(
"id" => 3, // 3 on purpose
"something" => "Hello, mom?"
)
);
$secondArray = array(
array(
"id" => 1,
"thing" => null
),
array(
"id" => 2,
"thing" => null
)
);
foreach ($firstArray as $key => $value) {
foreach ($secondArray as $k => $v) {
if ($value['id'] == $v['id']) {
echo "Found one!\n------\n" . print_r($value, true) . "\ncontains the same ID as\n\n" . print_r($v, true) . "\n------\n";
// you may also do this if you want
// $secondArray[$k]['thing'] = $value['id'];
// this would set "thing" (in the second array) to the value of "id" (in the first array)
}
}
}
EDIT Here is a second example, displaying how you could use it as a function... PHPaste Snippet.
Note: I used the OLD array syntax because it's easier for new programmers to understand.
So, essentially what you are doing is iterating through each item in $firstArray, comparing it to each item in $secondArray, by doing a nested foreach within side the first foreach if that makes sense...?
Here is what I just said in simple form:
go through each item in array 1
--> compare it to each item in array 2
You may also notice my use of PHP's lovely function, print_r(). This displays objects and arrays in a slightly, clearer, form.
You can also see that I am getting the values from within the arrays by using $value['id'] and $v['id']. These were defined in my foreach declaration, foreach ($firstArray as $key => $value); $value is an associative array, so you can simply get a value by key just as you would if you created an array like this:
$myArray = [
"id" => 1
];
and grabbed values like this:
echo $myArray['id']; // 1
Hopefully this helped.
I have some content types (nodes) that are attached to various taxonomies. For specific node types, I want to do some validation on the taxonomy. I do not want to hard-code the nodes types and their corresponding fields that reference the taxonomy. So I put them in array.
However, I am unable to dereference the field names. I've tried double $$, quotes, etc, but can't get it to work. Is what I want to do possible?
Below is a standalone PHP that I am trying to get to work.
<?php
$node = (object) array(
'nid' => NULL,
'vid' => NULL,
'uid' => '1',
'type' => 'price_document',
'language' => 'und',
'field_taxonomy_price' => array(
'und' => array(
array(
'tid' => '94'
)
)
),
);
$nodes_to_check = array("price_document" => "field_taxonomy_price",
"package" => "field_taxonomy_package",
);
if (array_key_exists($node->type,$nodes_to_check)) {
$taxonomy_field = $nodes_to_check[$node->type];
print_r($taxonomy_field);
$tid = $node->field_taxonomy_price ['und'][0]['tid']; // <- this works but, how
//$tid = $node->"$$taxonomy_field" ['und'][0]['tid']; <- can I deref variable?
}
?>
Well, you can do this:
$taxonomy_field = $nodes_to_check[$node->type];
$tid = $node->{$taxonomy_field}['und'][0]['tid];
You don't need the double dollar signs. That's in case you want to do things like this:
$dog = "I am a dog";
$var = "dog";
$$var = "Now I'm a pussycat";
echo $dog; // Output: Now I'm a pussycat