从多维数组PHP中删除Int键和值

时间:2015-11-26 10:28:53

标签: php arrays

我有这个数组(我不能改变它):

   array(3) {   
[0]=>
  array(8) {
    ["kampania"]=> string(6) "dasdas"
    [0]=> string(6) "dasdas"
    ["300x250"]=> int(1)
    [1]=> int(1)
    ["160x600"]=> int(2)
    [2]=> int(2)
    ["728x90"]=> int(3)
    [3]=> int(3)
  }
  [1]=>
  array(8) {
    ["kampania"]=> string(12) "aaaaaaaaaaaa"
    [0]=> string(12) "aaaaaaaaaaaa"
    ["300x250"]=> int(4)
    [1]=> int(4)
    ["160x600"]=> int(5)
    [2]=> int(5)
    ["728x90"]=> int(6)
    [3]=> int(6)
  }
  [2]=>
  array(8) {
    ["kampania"]=> string(20) "AAAAAAAAAAAAAAAAAAAA"
    [0]=> string(20) "AAAAAAAAAAAAAAAAAAAA"
    ["300x250"]=> int(7)
    [1]=> int(7)
    ["160x600"]=> int(8)
    [2]=> int(8)
    ["728x90"]=> int(9)
    [3]=> int(9)
  }
}

正如你所看到的,我得到了重复的值,因为数组作为定义的键然后是一个整数键。

如何创建一个函数,它将从数组中删除整数键和值并返回一个已经“干净”的新数组

期望的结果应该是这样的:

array(3) {
    [0]=>
      array(8) {
        ["kampania"]=> string(6) "dasdas"
        ["300x250"]=>  int(1)
        ["160x600"]=>  int(2)
        ["728x90"]=>   int(3)
      }
      [1]=>
      array(8) {
        ["kampania"]=> string(12) "aaaaaaaaaaaa"
        ["300x250"]=>  int(4)
        ["160x600"]=>  int(5)
        ["728x90"]=>   int(6) 
      }
      [2]=>
      array(8) {
        ["kampania"]=> string(20) "AAAAAAAAAAAAAAAAAAAA"
        ["300x250"]=> int(7)  
        ["160x600"]=> int(8) 
        ["728x90"]=>  int(9) 
      }
    }

谢谢大家!我真的很抱歉问这个问题,但是我已经花了很多时间试图自己解决它

3 个答案:

答案 0 :(得分:2)

function unset_num_keys($array)
{
    $array_out = array();
    foreach($array AS $k => $v)
    {
        if(is_array($v))                            //value is an array, so clean it
        {
            $array_out[$k] = unset_num_keys($v);    //clean "child" arrays
        }
        elseif(!is_numeric($k))
        {
            $array_out[$k] = $v;                    // key is "safe"
        }
    }
    return $array_out;
}

然后

$clean_array = unset_num_keys($old_array);

答案 1 :(得分:1)

循环抛出数组,如果key(index)是数字,则从数组中删除该项。

foreach($level1_array as &$arr){

  foreach ($arr as $key => $value) {
    if (is_int($key)) {
      unset($arr[$key]);
     }
   }
}

示例

<?php 
$level1_array = array(

    array(
            "smith",
            "name" => "smith",
            "20",
            "age"=>20
        ),
    array(
            "smith",
            "name" => "smith",
            "20",
            "age"=>20
        ),
     array(
            "smith",
            "name" => "smith",
            "20",
            "age"=>20
        ),
);

foreach($level1_array as &$arr){

 foreach ($arr as $key => $value) {
   if (is_int($key)) {
     unset($arr[$key]);
    }
  }
}

var_dump($level1_array);
?>

答案 2 :(得分:0)

您可以尝试以下代码:

//$data = $yourData;
$newData = array();
foreach($data as $v){
    array_push($newData,array_flip($v));
}