簡體   English   中英

如何使用php將多維數組轉換為單個數組?

[英]How to convert multi-dimensional array into single array using php?

實現數據庫查詢后,我將在下面獲取多維數組。

二維陣列

Array
(
    [0] => Array
        (
            [t1] => test1
        )

    [1] => Array
        (
            [t2] => test2
        )

    [2] => Array
        (
            [t3] => test3
        )

    [3] => Array
        (
            [t4] => test4
        )

    [4] => Array
        (
            [t5] => test5
        )

)

但我想將其轉換為一維數組,例如下面的格式。

一維陣列

Array (
    t1 => test1
    t2 => test2
    t3 => test3
    t4 => test4
    t5 => test5
)

請幫我這樣做

我認為您可以使用array_reduce()函數。 例如:

   $multi= array(0 => array('t1' => 'test1'),1 => array('t2' => 'test2'),2 => array('t3' => 'test3'),3 => array('t4' => 'test4'));
   $single= array_reduce($multi, 'array_merge', array());
   print_r($single);  //Outputs the reduced aray

您可以使用以下方法:

$newArray = array();
foreach($arrayData as $key => $value) {
    foreach($value as $key2 => $value2) {
        $newArray[$key2] = $value2;
    }
}

其中$ arrayData是您的數據庫數據數組,而$ newArray將是結果。

假設源數組是數組的數組,並且沒有相同的鍵:

<?php
$src = [
    ['t1'=>'test1'],
    ['t2'=>'test2'],
    ['t3'=>'test3'],
    ['t4'=>'test4'],
    ['t5'=>'test5'],
];
$result = call_user_func_array('array_merge', $src);

通過var_dump()得到的結果:

array(5) {
  ["t1"]=>
  string(5) "test1"
  ["t2"]=>
  string(5) "test2"
  ["t3"]=>
  string(5) "test3"
  ["t4"]=>
  string(5) "test4"
  ["t5"]=>
  string(5) "test5"
}

您可以使用array_reduce()更改數組的值。 在回調中,使用key()獲取項目的key()並使用reset()選擇第一個項目。

$newArr = array_reduce($oldArr, function($carry, $item){
    $carry[key($item)] = reset($item);
    return $carry;
});

演示中檢查結果

試試這個功能,

function custom_function($input_array)
{
    $output_array = array();
    for ($i = 0; $i < count($input_array); $i++) {
        for ($j = 0; $j < count($input_array[$i]); $j++) {
            $output_array[key($input_array[$i])] = $input_array[$i][key($input_array[$i])];
        }
    }
    return $output_array;
}

$arr = custom_function($arr);
print_r($arr);

試試看,它將起作用。

嘗試這樣的事情對於您有限的用例,可以這樣做:

$oneDimensionalArray = array_map('current', $twoDimensionalArray);

當子數組對此有很多條目時,可以將其更一般化:

$oneDimensionalArray = call_user_func_array('array_merge', $twoDimensionalArray);

如果您不希望保留正確的數組鍵,可以使用它

function flattenA(array $array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}
print_r(flattenA($arr));
// Output
Array
(
    [0] => test1
    [1] => test2
    [2] => test3
    [3] => test4
    [4] => test5
)

除此以外

function flattenB(array $array) {
    $return = array();
    array_walk_recursive($array, function($v,$k) use (&$return) { $return[$k] = $v; });
    return $return;
}
print_r(flattenB($arr));
// Output
Array
(
    [t1] => test1
    [t2] => test2
    [t3] => test3
    [t4] => test4
    [t5] => test5
)

沙盒上同時檢查

從類似問題的答案

你可以用這個

<?php
$temp = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));

$result_array = array();
foreach ($temp as $val) {
  foreach ($val as $key => $inner_val) {
    $result_array[$key] = $inner_val;
  }
}
print_r($result_array);

?>
// Multidimensional array
$arrdata = Array(
    '0' => Array(
        't1' => 'test1'
    ) ,
    '1' => Array(
        't2' => 'test2'
    ) ,
    '2' => Array(
        't3' => 'test3'
    )
);

// Convert to a single array
$data = array();
foreach($arrdata as $key => $value) {
    foreach($value as $key1 => $value1) {
        $data[$key1] = $value1;
    }
}
echo $data;

嘗試數組映射功能。

$singleDimensionArray = array_map('current',$multiDimensionArray);

對於您的特定情況,我將使用array_reduce ,其中我通過一個空數組設置初始值

array_reduce($arr, function($last, $row) {
                return $last + $row;
            }, array());

PHP 7.4之后

array_reduce($arr, fn ($last, $row) => $last + $row, array());

結果:

array(
    't1' => 'test1',
    't2' => 'test2',
    't3' => 'test3',
    't4' => 'test4',
    't5' => 'test5'
)

嘿@Karan Adhikari簡單如下所示:

<?php
    $arr1 = array(array("t1" => "test1"), array("t2" => "test2"), array("t3" => "test3"), array("t4" => "test4"), array("t5" => "test5"));
    echo "<pre>";
    print_r($arr1);//before
    $arr2 = array();
    foreach($arr1 as $val){ 
        $arr2 = array_merge($arr2, $val);
    }
    echo "<pre>";
    print_r($arr2); // after you get your answer

請嘗試以下功能:

function array_merging($multi_array) { 
    if (is_array($multi_array)) { 
        $new_arr = array(); 
        foreach ($multi_array as $key => $value) { 
            if (is_array($value)) { 
            $new_arr = array_merge($new_arr, array_merging($value)); 
            } 
            else { 
                $new_arr[$key] = $value; 
            } 
        } 
        return $new_arr; 
    }
    else {
        return false;
    }
}

使用此功能:

$your_multi_arr = array(array(array('t1'=>'test1'),array('t2'=>'test2'),array('t3'=>'test3'),array('t4'=>'test4')));
$arr1 = array_merging($your_multi_arr);
echo "<pre>";
print_r($arr1);

希望這對您有用。

您可以嘗試使用PHP while listeach遍歷數組。 我從PHP網站上獲取了示例代碼,第二個示例可以在此處查看

$arr = [['t1' => 'test1'],['t2' => 'test2'],['t3' => 'test3'],['t4' => 'test4'],['t5' => 'test5']];
$output = [];
while (list($key, $val) = each($arr)) {
    while (list($k, $v) = each($val)) {
    $output[$k] = $v;
}
}
print_r($output);

創建的輸出為

Array
(
    [t1] => test1
    [t2] => test2
    [t3] => test3
    [t4] => test4
    [t5] => test5
)

您可以在此沙盒示例中自行進行測試

遍歷數組並保存鍵值, 此處為Live Demo

<?php
    $array = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
    $result = [];
    array_walk($array, function($value) use(&$result){
        foreach($value as $k => $v)
        {
            $result[$k] = $v;
        }
    });
    var_dump($result);

這將解決問題

$array = array_column($array, 't1');

注意:此函數array_column在PHP 5.5中引入,因此在早期版本中將不起作用。

`$result = "Query";  $key_value = array();`

      foreach ($result as $key => $value) {
          $key_value[$key['']] = $value[''];
      }
     //for checking //echo "<pre>" ; print_r($key_value) ; exit;
      return $key_value;

請填寫$ key ['在字段的sql查詢中給定的名稱']$ value ['在sql的查詢字段中給定的名稱'] (兩者相同)

我會建議將所有二維數組轉換為一維數組的方式。

<?php

  $single_Array = array();

  //example array
  $array = array(
    array('t1' => 'test1'), 
    array('t2' => 'test2'), 
    array('t3' => 'test3'), 
    array('t4' => 'test4'), 
    array('t5' => 'test5'));

 $size = sizeof($array);

 //loop to fill the new single-dimensional array
 for($count = 0; $count<sizeof($array);$count++)
 {
    //take the key of multi-dim array
    $second_cell = key($array[$count]);
    //set the value into the new array
    $single_array[$count] = $array[$count][$second_cell];
 }

 //see the results
 var_dump($single_array);


?>

使用此腳本,我們可以獲取鍵和值來創建新的一維數組。希望對您有所幫助。

您可以在此處看到示例: 數組轉換演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM