Remove first levels of identifier in array

杀马特。学长 韩版系。学妹 提交于 2019-11-28 23:52:54
prodigitalson

The problem here is preserving the keys for the identifier you want. You have some names strings that have the same key (like Blå and Röd). You either need to store these in an array or be willing to lose the key.

Example with php5.3:

$processed = array_map(function($a) {  return array_pop($a); }, $arr);

This will give you:

[0] => Röd
[1] => Blå
[2] => Bobo
[3] => Grön
[4] => Sten
[5] => Vit
[6] => Guld
[7] => Lyxig

It has become clear the keys on the inner array need to be preserved because they are some kind of id. With that said you must change the end structure you're going for because you can have 2 of the same key in a single array. The simplest structure then becomes:

[8] => Array
        (
            [0] => Röd,
            [1] => Blå,
            [2] => Vit,
            [3] => Grön
        )

[6] => Array
        (
            [0] => Bobo,
            [1] => Lyxig
        )

[7] => Array
        (
            [0] => Sten,
            [1] => Guld
        )

To get this structure a simple loop will work:

$processed = array();
foreach($arr as $subarr) {
   foreach($subarr as $id => $value) {
      if(!isset($processed[$id])) {
         $processed[$id] = array();
      }

      $processed[$id][] = $value;
   }
}

PHP array_column

$new_array = array_column($old_array,0);

This will retrieve the value at index 0 for each array within $old_array. Can also be using with associative arrays.

Try to merge array with splat operator:

   print_r(array_merge(...$array));

use :

  public function remove_level($array) {
      $result = array();
      foreach ($array as $key => $value) {
        if (is_array($value)) {
          $result = array_merge($result, $value);
        }
      }
      return $result;
}

which will return second level array values in the same order of the original array. or you can use array_walk

   $results = array();
   array_walk($array, function($v, $k) use($key, &$val){
              array_merge($results, $v);
    });
Luc
foreach($array as $key=>$val) { 
  $newarr[$val] = $array[$key][$val]; 
} 

untested!

Check this out this is what expected result

<?php
$arrData = array(
"5" => array
        (
            "8" => "Vit"
        ),

"6" => array
        (
            "7" => "Guld"
        )
);
foreach($arrData as $key=>$value):
    foreach($value as $k=>$v):
     $data[$k] = implode(',',$arrData[$key]);
    endforeach;
endforeach;


print_r($data);
?>

Below code will also achieve the same result.

$resultArray = array_map('current',$inputArray);

OR

$resultArray = array_map('array_pop',$inputArray);

Note: I have ignored OP's expected result keys. Because it is not possible to have the same keys in the array. The last key will replace the previous one if the same.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!