update post meta in WordPress with array? - php

How to update the post meta with array in wordpress.
For Example I tried this one to
$mail_list_array1 = get_post_meta($_POST['productid'], 'notify_emailsse');
$mail_list_array[] = $_POST['notifyaddress'];
$mail_list_arrays = array_merge($mail_list_array1, $mail_list_array);
update_post_meta($_POST['productid'], "notify_emailsse", $mail_list_arrays);
Now It returning the output as this way
array(1) {
[0]=> array(2) {
[0]=> array(2) {
[0]=> string(0) ""
[1]=> string(10) "t43tsdtret"
} [1]=> string(21) "weyriweyriynbdkxhfkds"
}
}
But I want this way
array(1) {
[0] => 'Email 1',
[1]=>'Email 2',
....}
How can i achieve that using post meta of wordpress. The reason what i am achieving for example:
If the user enter his email in the text field and i want to save the email in a one meta, same thing some other user also enter his email then that email should append as in common meta of wordpress. Shortly means saving multiple values into the same meta key.
Any Suggestion would be great.
Thanks,
vicky

I'm not sure about your purpose, but easiest will be to implode() arrays and then serialize() your post meta. After reading post meta do the opposite, to have data as an array: unserialize() and explode()

Related

PHP and Pods: Combine array values only into new array

Long time user, first time poster. The forums here have got me out of a lot of trouble but I'm really stuck on this one.
I'm using Pods for a Custom Post Type that has a Custom Field where a user can enter a numeric value. eg. or 4 or 2 etc
I want to display the total sum of this Custom Field across all user made posts on the front end. To achieve this I'm using a Pods Template to make a short code for the front end, but to do the calculation I'm using PHP.
So my current PHP is:
function jobs_total ($id) {
$pods = pods ('pledged_job', $id);
$jobs = ($pods->field ('jobs_pledged'));
$a = ($jobs);
$b = explode(' ', $a);
var_dump($b);
}
And the result I get so far is:
array(1) { [0]=> string(1) "5" }
array(1) { [0]=> string(1) "4" }
array(1) { [0]=> string(1) "2" }
array(1) { [0]=> string(1) "7" }
How do I take the numeric values from "_", which are correctly appearing from post entries, and combine them in a new array so I can perform an 'array_sum' and return the total of those numbers?!
I'm a PHP novice so I'm not sure if this is obvious or if it's a clash between Pods terms and standard PHP.
Thanks in advance!!
Final code wrapped in shortcode to allow for displaying on the frontend through Elementor
function jobs_shortcode () {
$jobs = get_posts(array(
'post_type' => 'pledged_job',
'post_status' => 'publish',
'numberposts' => -1, ));
$total = 0;
foreach ($jobs as $field) {
$total += (int) get_post_meta($field->ID, 'jobs_pledged', true);
}
echo $total;
}
add_shortcode( 'jobs', 'jobs_shortcode' );

Codeigniter query returns record with null id. Which shouldn't be possible

I have been trying to solve this problem for a long time already. I tried searching for an answer in stackoverflow, google and other sources but I didn't manage to find something that could lead me to the solution of the problem. I really hope you can help me. Thanks in advance.
Im using Codeigniter 3
My query in codeigniter is as shown here bellow:
$this->db->select($fields)
->from("usuario as u")
->join("usuario_info as ui ", "ui.idusuario = u.idusuario","left");
$this->db->where("usua_url",$this->url_usuario);
return $this->db->get(); //last line
I do get results from the query with data from a record which has an id (in the database is a PK and can't be NULL
My compiled query from CI is:
SELECT * FROM `usuario` as `u` LEFT JOIN `usuario_info` as `ui` ON `ui`.`idusuario` = `u`.`idusuario` WHERE `usua_url` = 'heri'
And my result is the following after applying result_array method (I censored some field names and its values, you know..):
array(9) {
["idusuario"]=> NULL
["other_field1"]=> string(9) "censored"
["other_field2"]=> string(60) "censored"
["other_field3"]=> string(26) "censored"
["other_field4"]=> string(19) "censored"
`["other_field5"]=> string(7) "censored"
["other_field6"]=> string(4) "censored"
["other_field7"]=> NULL
["other_field"]=> NULL
}`
When I copy and paste exactly the same query into DataGrip or Workbench I get the same results except for idusuario, the results look like:
array(9) {
["idusuario"]=> 1
["other_field1"]=> string(9) "censored"
["other_field2"]=> string(60) "censored"
["other_field3"]=> string(26) "censored"
["other_field4"]=> string(19) "censored"
`["other_field5"]=> string(7) "censored"
["other_field6"]=> string(4) "censored"
["other_field7"]=> NULL
["other_field"]=> NULL
}`
Well after trying something I thought wouldn't make any difference I got to the solution.
I had a method like for the query like this:
public function selectPerfilInfo($fields = "*"){
$this->db->select($fields);
$this->db->from("usuario as u");
$this->db->join("usuario_info as ui ", "ui.idusuario = u.idusuario","left");
$this->db->where("usua_url",$this->url_usuario);
return $this->db->get();
}
I was calling it like this in my controller:
//before calling the method I already set the `url_usuario` attribute of my class
$this->my_controller->selectPerfilInfo();
I changed the line above to this:
$this->my_controller->selectPerfilInfo("u.idusuario, u.other_field1");
After passing the specific fields to the function it returns the right results.
Im not sure why it happens and this leaves me a lot of doubts because I have used the same structure for getting records from other tables with no problems.
I'd appreciate if any of you could give me any information about it. Thanks

Understanding CodeIgniter objects and multidimensional arrays

I'm working on a project in CodeIgniter 2 and now I'm stuck on the most basic of concepts.
Model:
Get an object array from my table which contains all rows that match a specific value for a field named foo. There can be one or more rows that match. In this example, two rows.
public function get_sample($foo)
{
$query = $this->db->get_where('sample_db', array('foo' => $foo));
return $query->result();
}
Controller:
Assign the results and make output available to view.
public function view($foo)
{
$data['array'] = $this->sample_model->get_sample($foo);
$this->load->view('view', $data);
}
View:
echo var_dump($array); // for testing
echo $array[1]->text
var_dump() of $array:
array(2) {
[0]=> object(stdClass)#23 (4) {
["id"]=> string(1) "1"
["foo"]=> string(3) "bar"
["number"]=> string(4) "1234"
["text"]=> string(23) "This is content in 1234"
}
[1]=> object(stdClass)#24 (4) {
["id"]=> string(1) "2"
["foo"]=> string(3) "bar"
["number"]=> string(4) "9999"
["text"]=> string(23) "This is content in 9999"
}
}
The rendered ouput of echo $array[1]->text; is: This is content in 9999
And I understand how all that is working: $array[1]->text is the content of the text field in the array object with the index of 1, my second object.
However, I have a field called number and I want to access the object with a certain number and get its corresponding text value.
Example: How can I retrieve the value of text where the number is 9999? I cannot use $array[1]->text since I can never be sure of the object's position in the array. Something like $array['number' => '9999']->text, but I know that's not right. Maybe I need to loop through the array looking for a match?
This looks so simple yet everything I've tried has failed and resulted in various PHP errors. I've been studying the PHP manual here and here, but cannot seem to find anything about what I'm looking to do, or maybe I'm just misapplying what I'm reading. Any guidance is appreciated.
In addition to an answer using best practices following the MVC model, I'm hoping for a link to the proper page in the documentation, as well as pointing out any errors in my wording/terminology above.
EDIT:
This answer contains the actual code I used to solve my problem. Although, Yagi's answer was accepted because it put me in the right direction.
How about using this :
foreach ($array as $row) {
if ($row->number == '9999') {
echo $row->text;
}
}
Loop through the array, and find the number object value of 9999 and get the text
Why don't you just to a query and search for that number (or order by that number?)
Either way, what you need is a multidimensional array search function (that iterates through array of object and returns the found field value combo )
Something like this (put this in helper)
function multi_array_search($array, $field, $value)
{
$results = array();
if (is_array($array))
{
if ($array->$field == $value) //chek the filed against teh value, you can do addional check s(i.e. if field has been set)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, multi_array_search($subarray, $key, $value)); //recurisve serach
}
return $results;
}
//than in view or in controller, depending where you need it
$result = multi_array_search($array, "number", "9999");
var_dump($result) will return or whether number of foudn instances
array() {
[0]=> object(stdClass)#24 (4) {
["id"]=> string(1) "2"
["foo"]=> string(3) "bar"
["number"]=> string(4) "9999"
["text"]=> string(23) "This is content in 9999"
}
}
you might be looking for something like this...
array_filter($array, function($o){ return $o->number == 9999; } );
http://php.net/manual/en/function.array-filter.php
EDIT
$o is the parameter in the callback function. each element of the array is passed to the callback function. if the function returns false, the element will be filtered out.
$arr = array(
(object) array(
'num' => 33,
'text' => 'hello',
),
(object) array(
'num' => 44,
'text' => 'world',
),
);
$filtered = array_filter($arr, function($o){ return $o->num == 33; });
echo $filtered[0]->text; // hello
as you stated, index will remain, so use array_values or array_shift. here's an example with function
function get_by_num($arr, $num){
return array_shift(array_filter($arr, function($o) use ($num) { return $o->num == $num; }));
}
$obj = get_by_num($arr, 44);
var_dump($obj);
// object(stdClass)#2 (2) { ["num"]=> int(44) ["text"]=> string(5) "world" }
in this case $obj will be either NULL if element is not found, or the first match. $num is transferred along so you can use any value. you can even improve it:
function get_first_match($arr, $field, $val){
return array_shift(array_filter($arr, function($o) use ($field, $val) { return $o->{$field} == $val; }));
}
$obj = get_first_match($arr, 'num', 44);
and now you can search any field. in your case
$obj = get_first_match($array, 'number', 9999);
Thanks to Yagi's answer, I came up with the following very simple solution. I loop through the array and assign the value of text to a new array with an index that matches the value of number. Then in the view file, I can access the text value based on this index.
Controller:
public function view($foo)
{
$data['array'] = $this->sample_model->get_sample($foo);
foreach ($data['array'] as $row) {
$data['result'][$row->number] = $row->text;
};
$this->load->view('view', $data);
}
View:
if (isset($result[9999])) echo $result[9999];

Is Possible Custom Select Field using ORM on Fuelphp?

I have a problem when I want to query table using ORM ,example I have article table with field id,author,text.
My code like this :
// Single where
$article = Model_Article::find()->where('id', 4);
print_r($article);
that't code will be fetch all field on table article, it's like select * from article where id = 4
Try Possibility
$article = Model_Article::find(null, array('id','title'))->where('id', 3);
the response is
object(Orm\Query)#89 (14) {
["model":protected]=>
string(10) "Model_Article"
["connection":protected]=>
NULL
["view":protected]=>
NULL
["alias":protected]=>
string(2) "t0"
["relations":protected]=>
array(0) {
}
["joins":protected]=>
array(0) {
}
["select":protected]=>
array(1) {
["t0_c0"]=>
string(5) "t0.id"
}
["limit":protected]=>
NULL
["offset":protected]=>
NULL
["rows_limit":protected]=>
NULL
["rows_offset":protected]=>
NULL
["where":protected]=>
array(1) {
[0]=>
array(2) {
[0]=>
string(9) "and_where"
[1]=>
array(3) {
[0]=>
string(5) "t0.id"
[1]=>
string(1) "="
[2]=>
int(3)
}
}
}
["order_by":protected]=>
array(0) {
}
["values":protected]=>
array(0) {
}
}
that's is not return id or title field.
but when i'm try by adding get_one() method
$article = Model_Article::find(null, array('id','title'))->where('id', 3)->get_one();
id is return , but title is not and another field, i don't know why ?
Reference
ORM Discussion FuelPHP it's say ORM currently will be select all column, no plans to change that at the moment.
My Problem
Select Custom Field using ORM like this select id,owner from article where id = 4 it's will be return only id & owner, Is Possible to get that using ORM on FUELPHP ?
Do not use
Model_Article::find()->
but use
Model_Article::query()->
The first one works but is considered an error situation which might change in future versions.
As of version 1.4 the ORM supports partial selects, using
Model::query()->select('id', 'value')->
The second parameter of find() is an array of conditions for the find, such as 'where' or 'order_by' clauses. There is no support for selecting column names in this array.
The Orm\Model fetches all column because it can't deal with incomplete / partials objects.
If you want a custom query, don't use the ORM, use the query builder for that.
DB::select('id','title')->from(Model_Article::table())->where('id', 4);
if you are trying to find out result like query "select * from article where id = 4"
$article = Model_Article::find()->where('id', 4)->get_one();
print_r($article);
and one more concept you should understand
get_one() returns only one record (as a object ).
get() returns multiple record ( in the form of array of objects ).
and if your field is not displaying then check the model Model_Article .this problem may be occur when you have not declared fields in properties list.
Fuelphp has been release new version , you can see this documentation , in my case fuelphp version is 1.2 and cannot select custom field using orm.
select custom field using orm is available since version 1.4
http://fuelphp.com/docs/packages/orm/crud.html
// Find only some columns
Model_Article::query()->select('id', 'name');
Model_Article::find('all', array('select' => array('id', 'name')));

creating multiple php arrays

I have a html form with checkboxes. Someone selects one or more checkboxes and hit the delete button then it will delete the files references out of the database and delete the files out of Amazon S3. This is the code I used to find all the checkboxes
$checkbox_select = JRequest::getVar('checkboxselect', '', 'POST'); //just a Joomla way of doing a $_POST with extra security
var_dump($checkbox_select); //this returns: array(2) { ["video_1.mp4"]=> string(2) "on" ["video_2.mp4"]=> string(2) "on" ["video_3.mp4"]=> string(2) "on"}
// Localize and sanitize each individual value
foreach (array_keys($checkbox_select) as $element) {
$deleteNames[] = $db->quote($element);
}
var_dump($deleteNames); //array(3) { [0]=> string(13) "'video_3.mp4'" [1]=> string(13) "'video_2.mp4'" [2]=> string(13) "'video_1.mp4'" }
My problem is with Amazon S3 and multiple file deletion. The format I need to put S3 deletion in is quite confusing:
$s3->delete_objects('mybucket', array(
'objects' => array( // accepts a *list* of one or more *hashes*
// a *hash* that contains a "key" key with a value, and maybe a "version_id" key with a value
array('key' => 'object (file) name'),
// a second hash representing a file
// a third hash representing a file
// and so on...
),
));
As far as I understand (from S3 delete_objects function) the final associated array has key as the actual key value. With the last var_dump I've got all video names in an array now I just need to convert that array to a bunch of arrays in this format:
array ('key' => 'video_1.mp4'),
array ('key' => 'video_2.mp4'),
array ('key' => 'video_3.mp4'),
...and so on
How can I create these arrays? Should I be using the first var_dump I have or the second (they both have the video file names listed)? Thanks in advance.
You can use foreach to loop over your array and create a new array in the desired format.
Example:
<?php
foreach (array_keys($checkbox_select) as $element) {
$deleteNames[] = array('key' => $db->quote($element));
}
Untested, may contain errors
have a look at this post in the php documentation for array_push(). You'll get a brief idea of how to achieve it.

Categories