Menu
  • HOME
  • TAGS

How can merge two arrays values in one array and save in database

Tag: php,arrays,wordpress,meta-key

I am working on WordPress upload meta fields. When user upload images the images are sized in two dimension one is "thumb" and one is "big" and they re sized very perfectly. I save both of images dimension path in database with different meta keys Like:

for thumb image wpc_resize_thumb_images and for big images wpc_resize_big_images.

When i save images path in DB it save perfectly.

Here is my code to save them in DB:

For big images

$product_img_path[$count]['wpc_resize_big_img'] = $upload_dir['url'].'/'.$resize_img_name;
update_post_meta($post->ID, 'wpc_resize_big_images', $product_img_path);

In Database it save like this:

meta_key

wpc_resize_big_images

meta_value

a:2:{i:1;a:1:{s:18:"wpc_resize_big_img";s:79:"http://localhost/test/wp-content/uploads/2015/06/Wallpaper_55-500x375.jpg";}i:2;a:1:{s:18:"wpc_resize_big_img";s:79:"http://localhost/test/wp-content/uploads/2015/06/Wallpaper_51-500x333.jpg";}}

and for thumb images

$product_img_path[$count]['wpc_resize_thumb_img'] = $upload_dir['url'].'/'.$resize_img_name;
update_post_meta($post->ID, 'wpc_resize_thumb_images', $product_img_path);

In Database it save like this:

meta_key

wpc_resize_thumb_images

meta_value

a:2:{i:1;a:1:{s:20:"wpc_resize_thumb_img";s:79:"http://localhost/test/wp-content/uploads/2015/06/Wallpaper_55-212x159.jpg";}i:2;a:1:{s:20:"wpc_resize_thumb_img";s:79:"http://localhost/test/wp-content/uploads/2015/06/Wallpaper_51-212x141.jpg";}}

And when i print them they show me result like this:

Big Imaegs

$wpc_resize_big_images = get_post_meta($post->ID, 'wpc_resize_big_images', true);
echo "<pre>";
    print_r($wpc_resize_big_images);
echo "</pre>";

and result is

Array
(
    [1] => Array
        (
            [wpc_resize_thumb_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_55-212x159.jpg
        )

    [2] => Array
        (
            [wpc_resize_thumb_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_51-212x141.jpg
        )
)

Thumb Images

$wpc_resize_thumb_images = get_post_meta($post->ID, 'wpc_resize_thumb_images', true);
echo "<pre>";
    print_r($wpc_resize_thumb_images);
echo "</pre>;

and result is

Array
(
    [1] => Array
        (
            [wpc_resize_big_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_55-500x375.jpg
        )

    [2] => Array
        (
            [wpc_resize_big_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_51-500x333.jpg
        )
)

Now My question that how can i merge and save in database both dimension with one meta key and when i print the meta key it gives me result like this

I want this

Array
(
    [1] => Array
        (
            [wpc_resize_thumb_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_55-212x159.jpg
            [wpc_resize_big_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_55-500x375.jpg
        )

    [2] => Array
        (
            [wpc_resize_thumb_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_51-212x141.jpg
            [wpc_resize_big_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_51-500x333.jpg
        )
)

Best How To :

When you are saving the multidimensional array you can use this code:

$product_img_path[$count]['wpc_resize_thumb_img'] = $upload_dir['url'].'/'.$resize_img_name;
$product_img_path[$count]['wpc_resize_bid_img'] = $upload_dir['url'].'/'.$resize_big_img_name;
update_post_meta($post->ID, 'wpc_images', $product_img_path);

That way you can get multidimentional array like you want:

Array
(
    [1] => Array
        (
            [wpc_resize_thumb_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_55-212x159.jpg
            [wpc_resize_big_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_55-500x375.jpg
        )

[2] => Array
    (
        [wpc_resize_thumb_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_51-212x141.jpg
        [wpc_resize_big_img] => http://localhost/test/wp-content/uploads/2015/06/Wallpaper_51-500x333.jpg
    )
)

Mixing

php

Set short_open_tag=On in php.ini And restart your Apache server...

Why am getting this error?: Unknown column 'firstname' in 'field list'

php,database,mysqli

$query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, $firstname, $lastname,$username,$password)"; you need single quote around text feilds in sql queries change above query to $query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, '$firstname', '$lastname','$username','$password')"; ...

Translating a character array into a integer string in C++

c++,arrays,string

If you want a sequence of int, then use a vector<int>. Using the key_char string, the values of the chars in it will serve as the initial value of the ints. std::vector<int> key_num(key_char.begin(), key_char.end()); Then, iterate over each character of key_num and convert it to the equivalent int value for...

How can I replace the white rectangle within an image using ImageMagick?

php,image-processing,imagemagick

I think you can locate the shape pretty accurately with a simple threshold, like this: convert image.jpg -threshold 90% result.jpg and you can then do a Canny edge detection like this: convert image.jpg -threshold 90% -canny 0x1+10%+30% result.jpg The next things I would be looking at are, using the -trim...

Symfony 2 unable to pass entity repository to form

php,forms,symfony2,runtime-error

You have not included the Symfony EnityRepository class at the top of your form file so PHP is looking for it in the same directory as your form class. Hence the error message. Add this to your form class (or qualify EntityRepository inline): use Doctrine\ORM\EntityRepository; ...

Ruby: How to copy the multidimensional array in new array?

ruby-on-rails,arrays,ruby,multidimensional-array

dup does not create a deep copy, it copies only the outermost object. From that docs: Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. If you are not sure how deep your object...

Get elements containing text from array

javascript,jquery,html,arrays,contains

You can use :contains selector. I think you meant either one of those values, in that case var arr = ['bat', 'ball']; var selectors = arr.map(function(val) { return ':contains(' + val + ')' }); var $lis = $('ul li').filter(selectors.join()); $lis.css('color', 'red') <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li>...

When I click to the next page on pagination,it goes to 404 error in codeigniter

php,codeigniter,pagination

in config.php $config['base_url'] = ''; $config['index_page'] = ''; in your router $route['news/(:any)'] = 'news/$1'; $route['news'] = 'news'; $route['default_controller'] = 'news/create'; $route['(:any)'] ='pages/view/$1'; and place .htaccess <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule> EDIT 01 <?php $data['title'] = 'Database Details'; $count = $this->news_model->record_count()...

how to escape php code in echo with javascript

javascript,php

You are mixing inline PHP with a PHP command (echo). When you are echoing a string, you do it just like normal, this means you can mix literal strings (the js you are manually typing) and the output of functions (like a json in this case): echo "<script type='text/JavaScript'> var...

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're "trying to allocate an array 64 bytes in size", you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

How to search images by name inside a folder?

php,mysql,image

This looks like a job for glob, which returns an array of file names matching a specified pattern. I'm aware of the other answer just posted, but let's provide an alternative to regex. According to the top comment on the docs page, what you could do is something like this:...

Laravel Interfaces

php,laravel,interface,namespaces

In my recent laravel 5 project, I'm used to prepare my logics as Repository method. So here's my current directory structure. For example we have 'Car'. So first I just create directory call it libs under app directory and loaded it to composer.json "autoload": { "classmap": [ "database", "app/libs" //this...

Cant submit form

javascript,php

Your PHP is checking if $_POST['submit'] contains a value. Your form does not contain a form element with the attribute name="submit", so therefore it fails and moves straight to the else statement. If you want to check if the form was posted then you should instead check for: if (!empty($_POST))...

how to multiply two column names using codeigniter validation rule

php,codeigniter,validation

You done need to do anything with your controller. Add this change your view to <script> function calculate() { var myBox1 = document.getElementById('crop_quantity').value; var myBox2 = document.getElementById('per_rate').value; var result = document.getElementById('income_amount'); var myResult = myBox1 * myBox2; result.value = myResult; } window.onload = calculate(); </script> <div class="control-group"> <label class="control-label">Crop Quantity</label>...

RecursiveIteratorIterator to fetch subdirectories

php

I would change if ( $dir->isDir() ) to if ( $dir->isDir() && $dir != $root) to remove the root directory...

How to modify CodeIgniter calendar to handle multiple events per day?

php,codeigniter,calendar

If you want to show all four boxes for the dates which has data, try to change the get_calendar_data() foreach as below, $content = ""; $lastDay = -1; $index = 0; foreach ($query->result() as $row) { if($lastDay != intval(substr($row->date_cal, 8, 2))){ if($index > 0 ){ if($content != ''){ $cal_data[$lastDay] =...

Javascript function to validate contents of an array

javascript,arrays

You can use a simple array based test like var validCodes = ['IT00', 'O144', '6A1L', '4243', 'O3D5', '44SG', 'CE64', '54FS', '4422']; function validItems(items) { for (var i = 0; i < items.length; i++) { if (validCodes.indexOf(items[i]) == -1) { return items[i]; } } return ''; } var items = ["IT00",...

PHP Regular Expressions Counting starting consonants in a string

php,regex

This is one way to do it, using preg_match: $string ="SomeStringExample"; preg_match('/^[b-df-hj-np-tv-z]*/i', $string, $matches); $count = strlen($matches[0]); The regular expression matches zero or more (*) case-insensitive (/i) consonants [b-df-hj-np-tv-z] at the beginning (^) of the string and stores the matched content in the $matches array. Then it's just a matter...

Create array from another with specific indices

javascript,arrays

You can use .map, like so var data = [ 'h', 'e', 'l', 'l', 'o', ' ' ]; var indices = [ 4, 0, 5, 0, 1, 2, 2 ]; var res = indices.map(function (el) { return data[el]; }); console.log(res); The map() method creates a new array with the results...

Javascript sort array of objects in reverse chronological order

javascript,arrays,sorting

As PM 77-1 suggests, consider using the built–in Array.prototype.sort with Date objects. Presumably you want to sort them on one of start or end: jobs.sort(function(a, b) { return new Date(a.ys, a.ms-1) - new Date(b.ys, b.ms-1); }) ...

Laravel 4.2 Sending email error

php,email,laravel,laravel-4

Closures work just like a regular function. You need to inject your outer scope variables into function's scope. Mail::send('invoices.mail', array($pinvoices,$unpinvoices), function($message) use ($email) { $message->to($email , 'Name')->subject('your invoices '); }); ...

How to pivot array into another array in Ruby

arrays,ruby,csv

Here is a way using an intermediate hash-of-hash The h ends up looking like this {"Alaska"=>{"Rain"=>"3", "Snow"=>"4"}, "Alabama"=>{"Snow"=>"2", "Hail"=>"1"}} myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] myFields = ["Snow","Rain","Hail"] h = Hash.new{|h, k| h[k] = {}} myArray.each{|i, j, k| h[i][j] = k } p [["State"] + myFields] + h.map{|k, v| [k] + v.values_at(*myFields)} output...

Composer dump-autoload gives preg_match error

php,composer-php,autoload

autoload should be moved out of require-dev: { "require-dev":{ "phpunit/phpunit":"4.5.*" }, "autoload":{ "psr-0":{ "Yii\\":"yii-1.1.14.f0fee9/" } } } You can test your composer.json file using composer validate. Your original file returned: ./composer.json is invalid, the following errors/warnings were found: require-dev.autoload : invalid value, must be a string containing a version constraint...

$http.get returns actual php script instead of running it (yeoman, grunt)

php,angularjs,pdo,gruntjs

Change $http.get('/scripts/php/articles.php') to $http.get('http://YOURDOMAIN.COM/scripts/php/articles.php') Off course you need to replace YOURDOMAIN.COM with localhost or any other domain you are using....

How do I display my mysql table column headers in my php/html output?

php,html,mysql,table,data

Note: You can just make a single file out of it to achieve your wanted output Use mysql_real_escape_string() to sanitize the passed-on value to prevent SQL injections You should use mysqli_* instead of the deprecated mysql_* API Form them in a single file like this (display.php): <html> <form method="post" name="display"...

How to pass a value from a page to another page in PHP

php

Only values that are sent by a form will be in the GET or POST array. From what you are showing I conclude that you don't want to show the field in your form, so make it hidden. Add this inside your form tag: <input name="price" type="hidden" value="'.$price.'" class="inputClass"> Also,...

MySQL Query returning strange values

php,mysql

You need to join by account_id and also question_id SELECT * FROM `quiz_questions` INNER JOIN `quiz_answers` ON `quiz_questions`.`account_id` = `quiz_answers`.`account_id` AND `quiz_questions`.`question_id` = `quiz_answers`.`question_id` WHERE `quiz_questions`.`account_id` = '1840979156127491' ORDER BY `quiz_questions`.`question_id` ASC LIMIT 5 ...

array and function php

php,arrays

$x and $y are only defined within the scope of the function. The code outside of the function does not know what $x or $y are and therefore will not print them. Simply declare them outside of the function as well, like so: <?php function sum($x, $y) { $z =...

Wordpress log out using URL and redirect to specify page

javascript,php,wordpress

Try wp_logout() function use the funtion . if($_GET['logout'] == 1) { ob_start(); error_reporting(0); wp_logout(); $redirect = wp_logout_url(); wp_safe_redirect( $redirect ); } ...

Error connecting to MSSQL using PHP

php,sql-server,pdo,odbc,sqlsrv

Change it to: $this->link = new PDO( "sqlsrv:Server={$this->serverName},{$this->port};Database={$this->db};", $this->uid, $this->pwd ); The default SQL Server port is 1433. Note the curly brackets, they allow for class variables....

pointer to pointer dynamic array in C++

c++,arrays,pointers

The valid range of indices of an array with N elements is [0, N-1]. Thus instead of for example this loop for (int i=1; i <= n; i++) ^^^^ ^^^^^^ you have to write for ( int i = 0; i < n; i++ ) As you used operator new...

php redirection working in chorme but not on firefox

php,google-chrome,mozilla

have you tried using header('location') function? example : <?php if (isset($_POST['putonline'])) { $query = "UPDATE user SET status= '1' WHERE id= '$new_id'"; $result = $cid-> query($query); if ($result== TRUE) { header("location:EidEmp.php"); die(); } else { echo "Failed"; } } ?> Edited : Maybe Change Your header function with javascript function...

compare today's date with unix timestamp value in database

php,mysql

If I understand correctly you have a unix timestamp in a varchar field and you can't change this. If you compare the unix timestamp directly you will only get results that match the exact second of the timestamp. You can use FROM_UNIXTIME() to convert the timestamp in a date value...

Click on link next link should be display on same page

javascript,php,jquery,html,css3

Ok, so i tried to decypher what you meant with your Question. To Clarify: He has this one page setup. inside the div Our Project, there are two Buttons or links Visit more. When clicked, he wants the About Section to be shown. All in all it is impossible for...

How to register global variable for my Laravel application?

php,laravel,laravel-5

Actually, you should reserve in config/app.php file. Then, you can add In the Service Providers array : 'Menu\MenuServiceProvider', In the aliases array : 'Menu' => 'Menu\Menu', Finally, you need to run the following command; php artisan dump-autoload I assume that you already added this package in composer.json Sorry, I didn't...

Dynamically select from a dynamically generated dropdown

php,html,select,drop-down-menu

It is because you aren't ending the value attribute, so your selected option becomes <option value="optionvalueselected" -- 'optionvalue' being the value of your selected option, and 'selected' being the attribute you want to set, but won't be set because you never ended value The following should work: <select name="course_id" id="course_id">...

Trying to rewrite mysql_* to pdo

php,mysql,pdo

I don't know the source of the array $arr = array();, but it is assigned to null before the insert query. So it means, literally you are inserting nothing into the database. So check your array well, maybe it was to be like $arr = array('name'=>'My Name', 'url'=>'url', 'email'=>'my email',...

Include both local and server at the same time

php

file_exists: http://php.net/manual/en/function.file-exists.php is_dir: http://php.net/manual/en/function.is-dir.php Best way to do that is use dirname(__FILE__) which gets the directory's full path of the current file in ether unix of windows format. Then we use realpath() which conveniently returns false if file does not exist. All you have to do is specify a relative...

Unable to configure Symfony (3rd party) bundle

php,symfony2,rss

I havent tried this bundle yet, but i think you need to tell doctrine that you want to save your newly created feed into the database: $feeds = new Feed; $reader->readFeed($url, $feeds, $date); $em = $this->getDoctrine()->getManager(); $em->persist($feeds); $em->flush(); return $this->render('default/index.html.twig'); UPDATE According to the docs if you want to use...

mysql_real_escape_string creates \ in server only not in local

php,sql

Your server has magic quotes enabled and your local server not. Remove it with the following sentence set_magic_quotes_runtime(0) As this function is deprecated and it will be deleted in PHP 7.0, I recommend you to change your php.ini with the following sentencies: magic_quotes_gpc = Off magic_quotes_runtime = Off If you...

Time format conversion with PHP

php,time

<?php $duration="1H10M5S"; $display=str_replace(array('H','M','S'), array(' Hour(s) ',' Minute(s) ',' Seconds'), $duration); echo $display; Output 1 Hour(s) 10 Minute(s) 5 Seconds Fiddle...

Codeigniter PHP Mailer, Sender Info

php,email,codeigniter-2,phpmailer,contact-form

Don't do that. It's effectively forging the from address and will fail SPF checks. Instead, use your own address as the From address, and add the submitted address as a reply-to address. In PHPMailer: $mail->From = '[email protected]'; $mail->addReplyTo($POST['emailfrom']); ...

Substring of a file

javascript,arrays,substring

To get your desired output, this will do the trick: var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d"; var array = file.split(", ") // Break up the original string on `", "` .map(function(element, index){ var temp = element.split('|'); return [temp[0], temp[1], index + 1]; }); console.log(array); alert(JSON.stringify(array)); The split converts...

PHP / MySQLi: How to prevent SQL injection on INSERT (code partially working)

php,mysql,mysqli,sql-injection,sql-insert

In the New PHP code snippet, you are still vulnerable to injections. You are using a prepared statement in the insert part, but you are not actually using the preparations strengths correctly. When creating a prepared statement, you create a query in which you add placeholders instead of the raw...

Merge and sum values and put them in an array

javascript,arrays,angularjs,foreach

You cannot store key-value pair in array. Use object to store key-value pair. See comments inline in the code. var obj = {}; // Initialize the object angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { if (obj[value.firstname]) { // If already exists obj[value.firstname] += value.distance;...

Php Mysql Query not working properly

php,mysql

No need to use union as it will give a lots of duplicate data What you want to achieve can be done with simple left join or inner join SELECT m.issue_name ,m.issue_type , m.priority ,m.status,m.description , m.start_date,m.end_date,m.duration, s.name as server_name,p.name as product_name from mod_networkstatus as m LEFT JOIN tblservers as...

access the json encoded object returned by php in jquery

php,jquery,ajax,json

Try: $.ajax({ url: "functions.php", dataType: "JSON", data: {id: id}, type: 'POST', success: function(json){ for(var i=0;i<json.length;i++){ alert(json[i].fname); } } }); ...

php include capitalization on files

php

Your local host must be Windows, that doesn't differentiate between upper and lower case in file names and your web server Unix Based which does, simple as that.

Blank screen on GridView

android,arrays,gridview

I executed ur code. Just add numberView.setTextColor(Color.BLACK); and it will work! :)...