2015-09-14 3 views
-1

Как я могу показать N/A только между элементами, которые имеют некоторые значения, отличные от N/A, и заменить N/A нулем во всех остальных случаях?Удалить указанное значение от начала и до конца массива

Количество ключей различное, и каждая подматрица может иметь ~ 300 ключей.

Пример:

Before  After 
N/A -> null 
N/A -> null  
10 -> 10 
N/A -> N/A 
20 -> 20 
N/A -> null  
N/A -> null  

Любые идеи, как написать функцию, которая может это сделать?

Вот мой код:

$dataCount = count($data) - 1; 
    $nextNotEmpty = null; 

    foreach ($data as $k => $element) { 
     $next = isset($data[$k + 1]) ? $data[$k + 1] : null; 
     if ($next) { 
      if ($nextNotEmpty) { 
       foreach ($nextNotEmpty as $id => $val) { 
        if ($val === 'N/A') { 
         $element[$k][$id] = ''; 
        } 
       } 
      } else { 
       $nextNotEmpty = $next; 
      } 
     } 

     if ($k === 0 || $k === $dataCount) { 
      foreach ($element as $key => $value) { 
       if ($value === 'N/A') { 
        $data[$k][$key] = ''; 
       } 
      } 
     } 
    } 

//source array: 
Array 
(
    [0] => Array 
     (
      [key1] => N/A 
      [key2] => 20 
      [key3] => N/A 
     ) 

    [1] => Array 
     (
      [key1] => 10 
      [key2] => 30 
      [key3] => N/A 
     ) 

    [2] => Array 
     (
      [key1] => N/A 
      [key2] => 40 
      [key3] => N/A 
     ) 

    [3] => Array 
     (
      [key1] => 30 
      [key2] => N/A 
      [key3] => N/A 
     ) 

    [4] => Array 
     (
      [key1] => N/A 
      [key2] => N/A 
      [key3] => N/A 
     ) 
//desired output array: 
Array 
(
    [0] => Array 
     (
      [key1] => null 
      [key2] => 20 
      [key3] => null 
     ) 

    [1] => Array 
     (
      [key1] => 10 
      [key2] => 30 
      [key3] => null 
     ) 

    [2] => Array 
     (
      [key1] => N/A 
      [key2] => 40 
      [key3] => null 
     ) 

    [3] => Array 
     (
      [key1] => 30 
      [key2] => null 
      [key3] => null 
     ) 

    [4] => Array 
     (
      [key1] => null 
      [key2] => null 
      [key3] => null 
     ) 
+0

Вы что-то пробовали? – Rizier123

+0

Да, я добавил код – gustas

ответ

0

Я нашел решение:

/** 
* Show N/A only in case when there are dates without prices between dates that have prices. 
* Otherwise replace N/A with empty string. 
* @param array $prices 
* @return array 
*/ 
private function removeNaValues($prices) 
{ 
    $removeNa = function(&$prices, $keys, $reverse = false) { 
     $len = count($prices); 

     if ($reverse) { 
      for ($i = $len - 1; $i > 0; $i--) { 
       if (!$this->prepareNaData($i, $prices, $keys)) { 
        break; 
       } 
      } 
     } else { 
      for ($i = 0; $i < $len; $i++) { 
       if (!$this->prepareNaData($i, $prices, $keys)) { 
        break; 
       } 
      } 
     } 
    }; 

    // remove some extra fields... 
    if (count($prices)) { 
     $keys = array_filter(array_keys($prices[0]), function($key) { 
      return !in_array($key, ['dateTimestamp', 'date']); 
     }); 
     // replace N/A's with empty string 
     $removeNa($prices, $keys); 
     $removeNa($prices, $keys, true); 
    } 

    return $prices; 
} 

/** 
* @param integer $index Current prices data index 
* @param array $prices Prices list 
* @param array $keys Series list to prepare data 
* @return int Count series to prepare 
*/ 
private function prepareNaData($index, &$prices, &$keys) { 
    foreach ($keys as $key => $val) { 
     if (is_numeric($prices[$index][$val])) { 
      unset($keys[$key]); 
     } else { 
      $prices[$index][$val] = ''; 
     } 
    } 

    return count($keys); 
} 
0

Попробуйте это:

foreach($array as $key => $value){ 
    $temp = $value; 
    // call function 
    replaceByNull($temp); 
    // reverse array 
    $temp = array_reverse($temp); 
    // call function twice 
    replaceByNull($temp); 
    // reverse twice to return at initial order 
    $array[$key] = array_reverse($temp); 
} 
function replaceByNull(&$array){ 
     $flag = true; 
     foreach($array as $k => $v){ 
      if($v == 'N/A' && $flag != false){ 
      $array[$k] = null; // REPLACE N/A by null :) 
      } else if($v != 'N/A' && $v != null){ 
      $flag = false; // Flag to stop replacing , number found 
      } 
     } 

} 
+0

Он не работает должным образом. Мне нужно удалить N/A только до первого и после последних значений для каждого ключа в массиве. N/A 10 N/A 20 N/A -> null 10 N/A 20 null – gustas

+0

Я отредактировал мой пост;) – Fky

0

Попробуйте это:

foreach($source_array as $key=>$value){ 
    for($i=0;$i<3:$i++){ 
    if($value[$i]=='N/A'){ 
     $source_array[$key]$value[$i]=NULL; 
    } 
    } 
} 
print_r($source_array); 
Смежные вопросы