search

散分?

从数据库读取数据,多数为一个行列整齐的二维数组,姑且叫它做矩阵数组吧
当读取后用php计算涉及很多纵向计算(例如对某字段求和),我看很多人都习惯 $array[记录][字段],其实读取时就应该想好怎样分配数组一维和二维的key

有时获取的矩阵数组格式固定了,例如来自某个API,我看到不少人还按着记录去求二维的值,更有甚者还用递归,看着真累,把行列交换一下再计算多方便啊

squareArray.php

<?phpclass squareArray{	public function swapRowCol($inArr)	{		$mit = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);		foreach($inArr as $key => $value) { $temArr = new ArrayIterator($value); $mit->attachIterator($temArr, $key); }		$arr = array();		foreach($mit as $item) array_push($arr,$item);		if (isset($inArr[0])) $arr = array_combine(array_keys($inArr[0]),$arr);		return $arr;	}	public function swapRowColWithKey($inArr)	{		foreach($inArr as $k1=>$v1) foreach($v1 as $k2=>$v2) $arr[$k2][$k1] = $v2;		return $arr;	}	public function intersect1st($arr1, $arr2, $key)	{		$arr[$key] = array_intersect($arr1[$key], $arr2[$key]);//match source's $key with target 		foreach($arr1 as $k=>$v) { if ($k == $key) continue; $arr[$k] = array_intersect_key($v, $arr[$key]); }		return $arr;	}	public function intersect2nd($arr1, $arr2, $key)	{		foreach($arr2 as $v) $tmpArr[] = $v[$key];		foreach($arr1 as $k=>$v) if(in_array($v[$key], $tmpArr)) $arr[$k] = $v;		return $arr;	}}?>


squareArray.sample.php
这是使用方法,写得简单了点,只是为了怕自己太久没用忘了,提醒一下写法而已
<?phpinclude('squareArray.php');//$array = array('id' => array('001', '002', '003'),'name' => array('张三', '李四', '王五'),'age' => array(22, 23, 11));  $array = array(array('id' => '001', 'name' => '张三', 'age' => 22),array('id' => '002', 'name' => '李四', 'age' => 23),array('id' => '003', 'name' => '王五', 'age' => 11));  $a = array(  0 => array('action_id' => 3),  1 => array('action_id' => 2),  2 => array('action_id' => 1),  3 => array('action_id' => 7),  4 => array('action_id' => 11),);$b = array(  0 => array('action_id' => 3, 'type' => 0, 'order_num' => 67),  1 => array('action_id' => 2, 'type' => 0, 'order_num' => 66),  2 => array('action_id' => 1, 'type' => 0, 'order_num' => 65),  3 => array('action_id' => 7, 'type' => 0, 'order_num' => 64),  8 => array('action_id' => 14, 'type' => 0, 'order_num' => 40),  13 => array('action_id' => 11, 'type' => 0, 'order_num' => 30),);//交换矩阵数组一维和二维键值例子$obj=new squareArray();$arr=$obj->swapRowCol($array);var_export($arr);//交换矩阵数组一维和二维键值例子(保留数值键名)$arr=$obj->swapRowColWithKey($b);var_export($arr);//根据指定key求二维数组矩阵数组交集(一维key)$key='action_id';$aa=$obj->swapRowCol($a);$bb=$obj->swapRowCol($b);$arr = $obj->intersect1st($bb, $aa, $key);//$b和$a自己定义吧,我懒得输入了$arr=$obj->swapRowCol($arr);var_export($arr);//根据指定key求二维数组矩阵数组交集(二维key)$key='action_id';$arr = $obj->intersect2nd($b, $a, $key);//$b和$a自己定义吧,我懒得输入了var_export($arr);exit;?>


如果发现bug就自己处理吧……


回复讨论(解决方案)

mark!

学习一下 感谢分享

巢状数组迭代该如何写?

巢状数组迭代该如何写?

那就不是我这个考虑的了,你也来贡献一个 

巢状数组是啥样的?
不考虑key的swapRowCol方法为啥比考虑key的swapRowColWithKey还复杂呢?
我经常这么用

		    public function swapRowCol($inArr)		    {		        return call_user_func_array('array_merge_recursive', $inArr);		    }

巢状数组是啥样的?
不考虑key的swapRowCol方法为啥比考虑key的swapRowColWithKey还复杂呢?
我经常这么用

		    public function swapRowCol($inArr)		    {		        return call_user_func_array('array_merge_recursive', $inArr);		    }


呵呵,如果输出正确当然你这个好
我当时是顺便练习SPL写的,之后就基本没用过swapRowCol(),一直都是用swapRowColWithKey(),所以就没再考虑优化了 

巢状数组是啥样的?
巢状我没理解错的话就是阵列中还嵌套阵列(cell arrays? nested arrays?),维度细致化来说就是超出二维了


巢状数组是啥样的?
巢状我没理解错的话就是阵列中还嵌套阵列(cell arrays? nested arrays?),维度细致化来说就是超出二维了

那如果不考虑key的话用#5方法不是正好

接触php一年了,第一次看到这个对象
$mit = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
咋整啊......

学习了,记号一下

收藏+学习。

谢谢lz分享

好铁。先搜藏了

很拥挤啊。换行,大括号。

很拥挤啊。换行,大括号。
显示器1920像素,所以,换行更挤 

过来学习一下

接触php一年了,第一次看到这个对象
$mit = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
咋整啊......

这句啥意思

好东东,值得收藏之


接触php一年了,第一次看到这个对象
$mit = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
咋整啊......

这句啥意思

自己查查手册 SPL一章

php5.5 增加了一个array_column函数,这个可以用用

php5.5 增加了一个array_column函数,这个可以用用
我也是昨天中午答人家一个问题查手册才看到,感觉从没用过,细看才知道新增加的
这咚咚不错,减少不少filter和遍历

谁给我的回复删了?

array_column ? 返回数组中指定的一列
自己写一个也很容易

$b = array(  0 => array('action_id' => 3, 'type' => 0, 'order_num' => 67),  1 => array('action_id' => 2, 'type' => 0, 'order_num' => 66),  2 => array('action_id' => 1, 'type' => 0, 'order_num' => 65),  3 => array('action_id' => 7, 'type' => 0, 'order_num' => 64),  8 => array('action_id' => 14, 'type' => 0, 'order_num' => 40),  13 => array('action_id' => 11, 'type' => 0, 'order_num' => 30),);print_r(array_column($b, 'action_id'));function array_column($ar, $key) {  return array_map(function($item) use ($key) { return @$item[$key]; }, $ar);}
Array
(
    [0] => 3
    [1] => 2
    [2] => 1
    [3] => 7
    [8] => 14
    [13] => 11
)

新手,还看不懂。

很有帮助!赞一个!

mark一下,有空看下

高手,技术分真多。

我去。。。玩了1个月还不到200分的路过。

都是牛人,学习一下

learn about,thanks

好多分啊

路过一观。。。。。

学习学习       

收藏…………

感谢分享,学习了

谢谢分享!还要不断学习啊!

学习了。。。。。哎 ,我们弱爆了啊

大清早就有好东西,感谢楼主

求 楼主帮助  php sql注入漏洞 不会。。

Statement
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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment