Home >Backend Development >PHP Tutorial >Example of converting one-dimensional array to two-dimensional array in PHP

Example of converting one-dimensional array to two-dimensional array in PHP

黄舟
黄舟Original
2018-05-22 10:48:0712106browse

The previous two articles "What is a php one-dimensional array, a detailed explanation of a php one-dimensional array example" and "What is a php two-dimensional array, a detailed explanation of a php two-dimensional array example 》Introducing one-dimensional arrays and two-dimensional arrays in detail. In this chapter, I will introduce the implementation of mutual conversion between one-dimensional arrays and two-dimensional arrays!

Without further ado, let’s first introduce the sample code for converting a one-dimensional array into a two-dimensional array:

<?php
header("Content-Type:text/html; charset=utf-8");
$asr[1] = array("a","b","c","d");
$asr[2] = array("a","b","c","d");
$asr[3] = array("a","b","c","d");
$newarray = array();
foreach($asr as $a)
{
    $newarray[] = $a;
}
print_r($newarray);
?>

The output result is:

Array (
[0] => Array (
[0] => a
[1] => b
[2] => c
[3] => d )
[1] => Array (
[0] => a
[1] => b
[2] => c
[3] => d )
[2] => Array (
[0] => a
[1] => b
[2] => c
[3] => d )
)

2 ways to convert a two-dimensional array into a one-dimensional array:

How to convert the following two-dimensional array into a one-dimensional array.

<?php
header("Content-Type:text/html; charset=utf-8");
$msg = array(
  array(
    &#39;id&#39;=>&#39;45&#39;,
    &#39;name&#39;=>&#39;jack&#39;
  ),
  array(
    &#39;id&#39;=>&#39;34&#39;,
    &#39;name&#39;=>&#39;mary&#39;
  ),
  array(
    &#39;id&#39;=>&#39;78&#39;,
    &#39;name&#39;=>&#39;lili&#39;
  ),
);
?>

The first method:

foreach($msg as $k => $v){
        $ids[] = $id;
        $names[] = $name;
      }

The second method:

$ids = array_column($msg, &#39;id&#39;);
$names = array_column($msg, &#39;name&#39;);

The result of the above two solutions print_r($names); is:

Array(
  [0]=>jack
  [1]=>mary
  [2]=>lili
)

Note: array_column(); can have a third parameter, such as $n = array_column($msg, 'name', 'id');

print_r($n);The result is:

Array(
  [45]=>jack
  [34]=>mary
  [78]=>lili
)

【Related tutorial recommendations】

1. Relevant topic recommendations: "php array (Array)"

2 . Related video course recommendations: " Sort multiple arrays at the same time. Multidimensional arrays are first converted into one-dimensional arrays by value: array_multisort()"



The above is the detailed content of Example of converting one-dimensional array to two-dimensional array in PHP. For more information, please follow other related articles on the PHP Chinese website!

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