I am trying to remove Product element using unset from the array but it's not working. also, need to insert this array using MySql. How can I achieve this?
unset( $ar2['Product'] );
print_r($ar2);
Result showing with Product
Array
(
[0] => Array
(
[Product] => Resume, CV, vCard & Portfolio HTML5 Template
[Price] => 10
[Img] => http://localhost/envy-theme-new/wp-content/uploads/2019/01/cv.jpg
)
[1] => Array
(
[Product] => Runhill – Multipurpose Construction WP Theme
[Price] => 39
)
)
Your code should be
foreach ($ar2 as $array) {
unset( $array['Product'] );
}
Since you need to unset the key product from each element of the first array.
And to insert it you can use insert query inside the same loop.
foreach ($ar2 as $array) {
unset( $array['Product'] );
$sql = "insert into table_name column1,column2 values ($array['Price'],$array['Img'];";
}
I'm Assuming that you know how to insert values into MySql.
Otherwise use the following tutorial.
https://www.w3schools.com/php/php_mysql_insert.asp
Edit
Use this code inside your loop to remove multiple keys.
$keys = array('key1', 'key2');///all the keys you need to remove
foreach($keys as $key) {
unset($arr[$key]);
}
#kane
The error in your code is that you are not accessing the correct array index.
Array
(
[0] => Array
(
[Product] => Resume, CV, vCard & Portfolio HTML5 Template
[Price] => 10
[Img] => http://localhost/envy-theme-new/wp-content/uploads/2019/01/cv.jpg
)
[1] => Array
(
[Product] => Runhill – Multipurpose Construction WP Theme
[Price] => 39
)
)
In your array Product index occurs after a numeric index i.e.
You can use the approach of Yasii or you can try array_map to iterate over the array of array and unset Product key.
<?php
$data=array(
array(
'Product' => 'Resume, CV, vCard & Portfolio HTML5 Template',
'Price' => 10,
'Img' => 'http://localhost/envy-theme-new/wp-content/uploads/2019/01/cv.jpg'
),
array(
'Product' => 'Runhill – Multipurpose Construction WP Theme',
'Price' => 39
)
);
$data = array_map(function($arr){
unset($arr['Product']);
return $arr;
}, $data);
echo '<pre>';
var_dump($data);
As for insert PHP array to Mysql database you need to create an insert statement from the array values and have to handle missing index values like 'Img' key value is missing your second sub-array array
Before working with arrays learn about the best way to use arrays in php here:
https://code.tutsplus.com/tutorials/working-with-php-arrays-in-the-right-way--cms-28606
Using mysql ext to insert data into the db is no longer supported in PHP7.
Please use PDO instead.
A similar query is answered here:
Insert array into MySQL database with PHP
PDO Tutorial:
https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Related
I have a huge array in which keys are also not constant in most of the cases, but there are 3 keys that always constant (#name,#default_value,#value) and #default_value and #value is different i want to get these kind of sub arrays in 1 simple array , for this purpose i am using recursion in whole array and checking out if these 3 keys are present there i can print these values inside recursion easily but I am not able to get those values in return. So that i can precess them further.
$form=array();
$form['field_one']['#name']="field_one";
$form['field_one']['#default_value']="old";
$form['field_one']['#value']="new";
$form['field_two']['#name']="field_two";
$form['field_two']['#default_value']="old";
$form['field_two']['#value']="new";
$form['field_three']['#name']="field_three";
$form['field_three']['#default_value']="old";
$form['field_three']['#value']="old";
$form['thiscouldbeanotherarray']['idk']['field_four']['#name']="field_four";
$form['thiscouldbeanotherarray']['idk']['field_four']['#default_value']="old";
$form['thiscouldbeanotherarray']['idk']['field_four']['#value']="new";
$arr_get = get_updatedvalues($form,array());
var_dump($arr_get);
function get_updatedvalues($form,$fields) {
if (!is_array($form)) {
return;
}
foreach($form as $k => $value) {
if(str_replace('#','',$k) =='default_value' && ($form['#default_value'] != $form['#value'] ) ){
$fields['field'][$form['#name']] = array("name" => $form['#name'],"old_value" =>$form['#default_value'],"new_value" =>$form['#value']);
var_dump($fields);
}
get_updatedvalues($value,$fields);
}
return $fields;
}
If you run this code it will give you $arr_get > array (size=0), there i need all three values
If I understand correctly, you need to pass fields as a reference in order to change it:
function get_updatedvalues($form, &$fields) {
To do that, however, you'll need to change your initial call so that you have a variable to pass as the reference:
$array = [];
$arr_get = get_updatedvalues($form,$array);
Running this I get:
Array
(
[field] => Array
(
[field_one] => Array
(
[name] => field_one
[old_value] => old
[new_value] => new
)
[field_two] => Array
(
[name] => field_two
[old_value] => old
[new_value] => new
)
[field_four] => Array
(
[name] => field_four
[old_value] => old
[new_value] => new
)
)
)
I have a large multi-dimensional array with multiple occurrences of #options indexes. The following is a single array example:
FORM => Array
(
[#attached] => Array
(
[library] => quiz/quiz-form-styling
)
[text_0] => Array
(
[#type] => markup
[#markup] =>
Wherelese did Walter White work besides being a teacher?
)
[radio_1] => Array
(
[#type] => radios
[#options] => Array
(
[0] => An elder Care home
[1] => [A car wash]
[2] => A beauty saloon
[3] => For Skylers old boss
)
[#correct] => testing_correct_for radio
)
[text_2] => Array
(
[#type] => markup
[#markup] =>
)
)
In the example above, the parent array of #options is radio_1. But that is not always the case as the arrays are dynamically generated. There is no way to know in advance what the parent index would be but there is always an #options index.
What I'm trying to figure out is how to find and retrieve the data in all occurrences of #options. How can I do that?
I'd suggest iterating the set of form elements and checking if an inner #options key exists. If so, you can add the options to your array of all options.
$all_options = [];
foreach ($form_elements as $name => $settings) {
if (isset($settings['#options'])) {
$all_options[$name] = $settings['#options'];
}
}
I used the element name as key in the example code, because I thought it seemed like it would be convenient to know where the options came from, but you wouldn't have to do it that way. If you just wanted them all in one big list, you could merge them onto $all_options instead of appending them.
$all_options = array_merge($all_options, $settings['#options']);
This is assuming each of the values under FORM is an array representing one form element. If there is any nesting such that #options could appear at a deeper level, a recursive search could handle that, but if not, I think it's best to keep it simple.
You can try something like recursive function
Here is simple example for above case.
$alloptions = array();
function seach($searcharray){
foreach($searcharray as $key=>$value){
if($key == '#options'){
$alloptions[] = $searcharray[$key];
}else if(is_array($value)){
seach($value);
}
}
}
I'm using ACF Pro plugin for Wordpress and use repeater fields.
With this code I get all the field values and additional info in an array:
$fields = get_field_object('slideshow');
With this code I can narrow it down to what I want to achieve:
print_r($fields[value];
By now I get this array below:
Array
(
[0] => Array
(
[videoWebm] => /wc/data/uploads/sea.webm
[videoMp4] => /wc/data/uploads/sea1.mp4
[text] => Test1
[kund] => Kund1
[link1] =>
[link2] =>
)
[1] => Array
(
[videoWebm] => /wc/data/uploads/turntable.webm
[videoMp4] => /wc/data/uploads/turntable.mp4
[text] => Test2
[kund] => Kund2
[link1] =>
[link2] =>
)
)
it can grow more - like [2] => Array, [3] => Array etc.
I want to access all videoWebm & videoMp4 values.
As of now I know how to access a specific value - for example:
print_r($fields[value][0][videoWebm]);
But I can't figure out how to access all of them and put them in two new arrays. One for videoWebm values and one for videoMp4 values. The problem for me is the index value when I try to loop thru the array. I don't know if this really is the way to go...
Anyone suggestions?
Best, Niklas
You can use foreach:
foreach ($fields[value] as $field) {
$videoWebms[] = $field['videoWebm']
$videoMp4s[] = $field['videoMp4'];
}
Or as splash58 said, use array_column:
$vieoWebms = array_column($fields[value], 'videoWebm');
$vieoMp4s = array_column($fields[value], 'videoMp4');
I would highly recommend you learn about php's foreach, it is very powerful and widely used (maybe a little too widely).
https://www.google.com/search?q=php%20foreach
To get the value from repeater use this :
$slides = get_field('slideshow');
if($slides){
foreach($slides as $slide){
echo $slide['videoWebm'];
echo $slide['text'];
echo $slide['kund]'];
echo $slide['link1'];
echo $slide['link2'];
}
}
So I am working with wordpress and using the following code I get the following. I know this must be a basic question but I want to know what it means:
[1012] => Array ( [0] => 1 )
[1013] => Array ( [0] => 0 )
[1014] => Array ( [0] => 0 )
[1018] => Array ( [0] => 0 )
PHP:
<?php
$all_meta_for_user = get_user_meta(get_current_user_id());
print_r( $all_meta_for_user );
?>
This data is user's metadata https://codex.wordpress.org/Function_Reference/get_user_meta
As you say, this is your metadata. Two things here: first of all, I'll store all that data together inside a single key and I'll remove the uneeded single-element array:
[my_plugin] => Array( [1012] => 1, [1013] => 0 ...)
That lowers the possibility of your data mixing with other's plugin data, having conflicts, etc. Also, as second array is probably not needed, it will make access to it a little simpler.
When you have that, it's only a matter of accessing the value like this:
if ($all_meta_for_user['my_plugin'][$id] == 1) show_the_post()
where $id is the post ID.
To use a single key, I'll do something like this (untested):
$posts_meta_for_user = get_user_meta(get_current_user_id(), 'my_plugin', true);
if (is_array($posts_meta_for_user)) {
$posts_meta_for_user[$new_id] = $new_value;
update_user_meta(get_current_user_id(), 'my_plugin', $posts_meta_for_user);
} else {
$posts_meta_for_user = array($new_id => $new_value);
add_user_meta(get_current_user_id(), 'my_plugin', $awesome_level);
}
Notice that we get only the meta value named 'my_plugin' and test it already had a value by checking that is an array. If it is, we update it, and if it's not, we create a new one. $new_id is the post ID you want to store and $new_value the value.
i have array like
Array
(
[1] => Array
(
[user_info] => Array
(
[id] => 1
[name] => Josh
[email] => u0001#josh.com
[watched_auctions] => 150022 150031
)
[auctions] => Array
(
[150022] => Array
(
[id] => 150022
[title] => Title of auction
[end_date] => 2013-08-28 17:50:00
[price] => 10
)
[150031] => Array
(
[id] => 150031
[title] => Title of auction №
[end_date] => 2013-08-28 16:08:03
[price] => 10
)
)
)
so i need put in <td> info from [auctions] => Array where is id,title,end_date but when i do like $Info['id'] going and put id from [user_info] when i try $Info[auctions]['id'] there is return null how to go and get [auctions] info ?
Try:
foreach( $info['auctions'] as $key=>$each ){
echo ( $each['id'] );
}
Or,
foreach( $info as $key=>$each ){
foreach( $each['auctions'] as $subKey=>$subEach ){
echo ( $subEach['id'] );
}
}
Given the data structure from your question, the correct way would be for example:
$Info[1]['auctions'][150031]['id']
$array =array();
foreach($mainArray as $innerArray){
$array[] = $innerArray['auctions'];
}
foreach($array as $key=>$val){
foreach($val as $k=>$dataVal){
# Here you will get Value of particular key
echo $dataVal[$k]['id'];
}
}
Try this code
Your question is a bit malformed. I don't know if this is due to a lacking understanding of the array structure or just that you had a hard time to explain. But basically an array in PHP never has two keys. I will try to shed some more light on the topic on a basic level and hope it helps you.
Anyway, what you have is an array of arrays. And there is no difference in how you access the contents of you array containing the arrays than accessing values in an array containing integers. The only difference is that what you get if you retrieve a value from your array, is another array. That array can you then in turn access values from just like a normal array to.
You can do all of this in "one" line if you'd like. For example
echo $array[1]["user_info"]["name"]
which would print Josh
But what actually happens is no magic.
You retrieve the element at index 1 from your array. This happens to be an array so you retrieve the element at index *user_info* from that. What you get back is also an array so you retrieve the element at index name.
So this is the same as doing
$arrayElement = $array[1];
$userInfo = $arrayElement["user_info"];
$name = $userInfo["name"];
Although this is "easier" to read and debug, the amount of code it produces sometimes makes people write the more compact version.
Since you get an array back you can also do things like iterating you array with a foreach loop and within that loop iterate each array you get from each index within the first array. This can be a quick way to iterate over multidimensional array and printing or doing some action on each element in the entire structure.