PHP — Testing Array Value - arrays

I'm using checkboxes in Advanced Custom Fields for WordPress. I only have one value set for it, that being a value of 'Yes'
And so I have setup the following test:
<?php if (!in_array('Yes', get_field('banner'))) : ?>
However, for those posts that don't have a value specified, I get the following error:
Warning: in_array() expects parameter 2 to be array, boolean given in
/var/sites/d/dev-chwng.co.uk/public_html/wp-content/themes/chwng/loop-slideshow.php
on line 19
I imagine because for the items where 'Yes' isn't selected, that in turn means there is no array called 'banner' that has been set
I tried putting the whole thing inside a statement of <?php if (get_field('banner')) : ?> which prevents the error, but it stops the script working from how I need it (hard to explain).
Does anyone know how I can determine a value of 'Yes' without throwing an error?

You could additionally (first) verify that it's an array, using is_array():
<?php
$banner = get_field('banner');
if ( is_array($banner) && !in_array('Yes', $banner) ) : ?>
This will make the script move on to the else statement immediately, if get_field() doesn't return an array.

Due to how the WP plugin works, it seems the only way I could get it working how I need it was with
<?php if ( get_field('banner') == '' ) : ?>

Related

My code is showing ARRAY

I am using a plugin, using the following code could show user ratings:
<?php $users_rating = RWP_API::get_reviews_box_users_rating( $post_id, $reviews_box_id ); ?>
<?php echo $users_rating; ?>
But instead of showing the actual values, I am getting ARRAY writen on my web page.
Can anyone help me please?
Thank you,
Regards
You need to read the documentation to know how to use the API correctly.
Your call to RWP_API::get_reviews_box_users_rating tells me you're using the "Reviewer WordPress Plugin" from CodeCanyon.
The first step is looking up that method in the documentation: http://evographics.net/WEB_SERVER/reviewer-plugin-v-3-14-2.pdf
The documentation tells you to expect an array to be returned therefore it's up to you to display those values in a usable format.
$users_rating = RWP_API::get_reviews_box_users_rating( $post_id, $reviews_box_id );
// We're going to skip verifying we got back what was expected for the sake of the answer.
// Loop through each user score and display.
foreach ( $users_rating['score'] as $key => $score ) {
// Example of how an individual score could be displayed.
printf( 'Score %d: %d<br />', $key, $score );
}
Based strictly on your example the results of your get_reviews_box_users_rating() method is returning an array. You need to loop through the array itself and echo those values.
foreach($users_rating as $k => $rating){
//IF YOUR ARRAY CONTAINS OBJECTS
echo $rating->userRating;
//IF AN ASSOCIATIVE ARRAY
echo $rating['userRating'];
}
To see the structure of the array being returned you can use this:
print_r($users_rating);
That will let you know if your array is a stdObject Array or an associative array of elements.

wordpress how to retrieve a single custom field value from a custom field array

I have a custom fields that is actually an array.
I would like to get one single field value from this array.
When I do:
$meta = get_post_meta( get_the_ID(), 'my_fields_array');
and then
var_dump($meta); // debugging
I can see the array
How can I get one single value from this array?
If you just want to get a value from an array instead of using
var_dump
Just echo out the value that you need, starting from 0 e.g.
<?php
$meta = array('Best','Worst','Stuff');
echo $meta[1];
?>
In my case echo $meta[1] = Worst
now do the same for your code,if you just want to see the value that is
I think I've found a solution: the issue is that the custom fields values I need are actually serialized into a string. So if I unserialize them I'm able to get what I need:
$meta= get_post_meta( $post->ID, 'custom_field_array', true );
$myvalues = unserialize( $meta );
echo $myvalues[my_value];
It works

Codeigniter Extracting Information, Function Isn't Working

I'm attempting to extract information from my mysql database. I believe I'm properly joining tables (function syntax below) but when I try and display the extracted information inside of a view, nothing is showing up. I used var_dump and my array is saying
array (size=0) empty
I'm also getting these error messages as well.
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_show_all_averages.php
Line Number: 6
Severity: Notice
Message: Undefined offset: 0
Filename: views/view_show_all_averages.php
Line Number: 7
My question is, where do you think I'm going wrong. What are some steps I should take to go about fixing my issue? (syntax below) Thanks Everyone.
My Model_data function
function getJoinInformation($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
My Site Controller
public function getAllInformation($year,$make,$model)
{
if(is_null($year)) return false;
if(is_null($make)) return false;
if(is_null($model)) return false;
$this->load->model('model_data');
$data['allvehicledata'] = $this->model_data->getJoinInformation($year,$make,$model);
$this->load->view('view_show_all_averages',$data);
}
My View
<?php
var_dump($allvehicledata);
if(isset($allvehicledata) && !is_null($allvehicledata))
{
echo $allvehicledata->make. ' ' .$allvehicledata->model . "<br />";
$make = $allvehicledata[0]->make;
echo "$make";
// $state = $cities[0]->state;
// echo '<hr>';
foreach ($allvehicledata as $car)
{
echo anchor('site/getAllInformation/'.$car->year.'/'.$car->make.'/'.$car->model, $car->year.' '.$car->make.' '.$car->model, array('title'=>$car->make.' '.$car->model)).'<br>';
}
}
?>
Your notice errors are happening because you are returning an array from your model function, yet are calling the data like it is an object. If you only want to retrieve one row of data from the DB, use row() instead of result(). Read Generating Query Results for more info.
The query you're running is not failing, but it is not returning any results. Chances are your WHERE conditions are not being given the values that you assume they are (that's my guess, anyway).
Use echo $this->db->last_query() after you perform the DB query to see exactly what SQL is being sent, and use that to figure out what may be wrong and why the result set is empty.

cakephp Paginator -> sort - model option

I am having some issues sorting the table data by a field of a different model.
From here: http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html
It says I can add in the 'model' option but when I try:
echo $this->Paginator->sort('unit', 'Unit', array('model' => 'Unit'));
I get this error:
Warning (2): array_filter() expects parameter 1 to be array, null given [CORE/Cake/View/Helper/PaginatorHelper.php, line 395]
Warning (2): array_merge() [function.array-merge]: Argument #1 is not an array [CORE/Cake/View/Helper/PaginatorHelper.php, line 395]
Any idea what is going on here? The Main / default model is Card and I need to order by the Unit model for one of the column headings.
Thanks
If you are showing records in a list out of some tables, then you can use it via:
<?php echo $this->Paginator->sort('Unit.unit', 'Unit');
It will perfectly work without passing third argument model option.
Just a reminder for newer Versions: Associated models are not automatically loaded in CakePHP3s Paginator. Make sure you include the 'sortWhitelist' Option, see https://book.cakephp.org/3.0/en/controllers/components/pagination.html#control-which-fields-used-for-ordering
Please try below code
echo $this->Paginator->sort('Unit.unit', 'Unit', array('model' => 'Unit'));
Let me know if any.

cakephp invalidate element array

I am using cakephp. I have a form with an element array.
For ex:-
<textarea name="data[User][0][description]>
<textarea name="data[User][1][description]>
From the controller, I need to invalidate (manually) the array field if it is empty and need to show errors to the respective field.
What is the correct syntax for invalidating the field if it an element array ?
I know, the following will work for single element . How it will be for an element array ?
$this->User->invalidate("description");
Unfortunately you cannot invalidate the field with that function.
But what invalidate() does?
function invalidate($field, $value = true) {
if (!is_array($this->validationErrors)) {
$this->validationErrors = array();
}
$this->validationErrors[$field] = $value;
}
It just set validationErrors of the model.
So, you can do following in your Controller (but I also appeal you to move that validation in the Model):
$this->User->validationErrors[1]['description'] = 'Your error message';
The following code will invalidate the second description in the list.
HTH
You can type in view:
<?php
echo $this->Form->error("User.1.description");
?>
Thanks Nik,
your answer helped me, but halfway, because my problem was with a compound field by other subfields.
account_number {
bank_code,
bank_office,
check_digit,
account
}
In this case if we need put in validation error in one subfield, this is the solution:
$this->Model->validationErrors['account_number']['bank_code'][0] = 'Your message error';
I hope this help someone.
Regards.
I had similar problem, since it was for admin panel I showed error message on the first level of field i.e. for this portion only.
If you are validation on controller, just create an array of error with field name and error message, set it in controller and display message if in_array($field, $withErrorArray) in view.

Resources