Home Backend Development PHP Tutorial 详解WordPress中用于合成数组的wp_parse_args()函数_php技巧

详解WordPress中用于合成数组的wp_parse_args()函数_php技巧

May 16, 2016 pm 08:02 PM
wordpress array

wp_parse_args() 函数是 WordPress 核心经常用到的函数,它的用途很多,但最主要用来给一个数组参数(args)绑定默认值。

因为 wp_parse_args() 函数返回的一定是一个数组,所以他会把传入查询字符串和对象(object)自动转换成数组,给了使用者更加方便的条件,也增加了兼容性。

常见的 query_posts()、wp_list_comments() 和 get_terms() 函数都使用了 wp_parse_args() 函数来帮它给数组参数添加默认值。

用法

wp_parse_args( $args, $defaults );
Copy after login

参数

$args

(数组 | 字符串)(必须)查询字符串、对象或者数组参数,用来绑定默认值。

默认值:None

查询字符串:

type=post&posts_per_page=5&cat=1

Copy after login

数组:

array( 'type' => 'post', 'posts_per_page' => 5, 'cat' => '1' )

Copy after login

$defaults

(数组)(可选)数组参数的默认参数。

默认值:空字符串

例子

function explain_parse_args( $args = array() ){
 
  //$args 的默认值
  $defaults = array(
    'before' => '<div class="box">',
    'after' => '</div>',
    'echo' => true,
    'text' => 'wp_parse_args() 函数演示'
  );
 
  //绑定默认值
  $r = wp_parse_args( $args, $defaults );
 
  $output = $r['before'] . $r['text'] . $r['after'];
  if( !$r['echo'] ) return $output;
  echo $output;
}
 
//没有参数
explain_parse_args();//打印:<div class="box">wp_parse_args() 函数演示</div>
 
//字符串参数
$output = explain_parse_args( 'text=字符串参数&before=<div class="box-2">&echo=0' );
echo $output;//打印:<div class="box-2">字符串参数</div>
 
//数组参数
explain_parse_args( array( 'text' => '数组参数', 'before' => '<div class="box-3">' ) );//打印:<div class="box-3">数组参数</div>
还有另一种不使用第二个 $defaults 参数的用法,就是帮你把一个查询字符串、对象或者数组的变量直接转换成通用的数组,避免判断类型。

//字符串
$array = wp_parse_args( 'text=测试另一种用法&type=字符串' );
var_dump( $array );
/*
  array(2) {
    ["text"]=>
      string(21) "测试另一种用法"
    ["type"]=>
      string(9) "字符串"
  }
*/
 
//对象(object)
class args_obj{
 
  public $text = '测试另一种用法';
 
  public $type = '对象(object)';
 
  function func(){
    //转换成数组的时候对象里边的函数会被忽略
  }
 
}
$obj = new args_obj;
var_dump( $obj );
/*
object(args_obj)#2175 (2) {
  ["text"]=>
    string(21) "测试另一种用法"
  ["type"]=>
    string(18) "对象(object)"
}
*/

Copy after login

wp_parse_args函数源代码详解
wp_parse_args 函数的源代码比较简单,
依附于PHP 内置函数get_object_vars、array_merge与WordPress的wp_parse_str函数来实现,
以下是该函数的源代码:

/**
 * Merge user defined arguments into defaults array.
 *
 * This function is used throughout WordPress to allow for both string or array
 * to be merged into another array.
 *
 * @since 2.2.0
 *
 *第一个参数可以是 字符串、数组或对象(obj)
 * @param string|array $args Value to merge with $defaults
 *第二个参数为默认的预设值数组,必须是数组
 * @param array $defaults Array that serves as the defaults.
 *返回值将是一个数组
 * @return array Merged user defined values with defaults.
 */
function wp_parse_args( $args, $defaults = '' ) {
 if ( is_object( $args ) )
 //将接收的对象(obj)转换为数组
 $r = get_object_vars( $args );
 elseif ( is_array( $args ) )
 //如果是数组则不转换
 $r =& $args;
 else
 //将接收的字符串转换为数组
 wp_parse_str( $args, $r );
 if ( is_array( $defaults ) )
 return array_merge( $defaults, $r );
 return $r;
}
Copy after login

其中get_object_vars函数是用来返回由对象属性组成的关联数组。
array_merge函数用是将两个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP vs. Flutter: The best choice for mobile development PHP vs. Flutter: The best choice for mobile development May 06, 2024 pm 10:45 PM

PHP and Flutter are popular technologies for mobile development. Flutter excels in cross-platform capabilities, performance and user interface, and is suitable for applications that require high performance, cross-platform and customized UI. PHP is suitable for server-side applications with lower performance and not cross-platform.

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

Does wordpress need to be registered? Does wordpress need to be registered? Apr 16, 2024 pm 12:07 PM

WordPress requires registration. According to my country's "Internet Security Management Measures", websites that provide Internet information services within the country must register with the local provincial Internet Information Office, including WordPress. The registration process includes steps such as selecting a service provider, preparing information, submitting an application, reviewing and publishing, and obtaining a registration number. The benefits of filing include legal compliance, improving credibility, meeting access requirements, ensuring normal access, etc. The filing information must be true and valid, and must be updated regularly after filing.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

See all articles