Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

JohnnyBegood

Warning: Undefined offset: 3

Recommended Posts

Pessoal, Tô com problema nesse código: "Warning: Undefined offset: 3 and Undefined offset: 5, nesta linha (36): $cd [$ i] [$ id] [$ j]. =" $ Row ";

Já tentei com isset mas não dei jeito. Sei que este erro pode ocorrer com  array vazio mas o array tem dados.

O call stack do PHP tá apontando pro $j : 

$j =G:\XAMPP\htdocs\guardiao\inventario\Stackoverflow_1.php:36:int 3
$match = G:\XAMPP\htdocs\guardiao\inventario\Stackoverflow_1.php:36: array (size=0) -   empty

Alguém consegue me ajudar?

    }elseif(isset($id)){  // ignore all file header content
            If (($row_previous == true)and ($row_ob !== true)){   
            ++$j; //increment its index to insert variable value created for the additional lines
            $row="(Ob) ". (trim($row)); //create pre value variable
            $row_ob=true;
            $cd[$i][$id][$j].="$row ";  // concatenate to last element to new -linha (36)
        }else{
        $cd[$i][$id][$j].=" $row";  // concatenate to last element
        }
    }

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

no seu array você está pedindo a posição 3 e 5 e elas não existem.

Esse erro aparece quando alguma posição inexistente do array é requisitada.

 

Exemplo que dará esse mesmo erro:

$numeros = array("um","dois","tres");
echo $numeros[3];

 

Isso acontece porque eu só tenho as posições 0, 1 e 2 no array.

No seu caso, verifique o conteúdo do array...

Aplique um var_dump em todos os arrays que você possui para verificar qual está vazio.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá Guilherme, eu executei var_dump em todos os array e, agora, descobri que o array vazio é o $match[1].
Saberia me ajudar a contornar o erro?

O array tá cheio mas quando chega no final do arquivo (arquivo txt), ele fica com valor 0 - array (size=0) empty

Esse é o código anterior ao que citei antes:
 

    }elseif(preg_match('/^(\(..\)\s.*)/',$row,$match)){  // capture Cd data
        ++$j;  // this is a new innerarray element, increment its index
        $cd[$i][$id][$j]=$match[1];  // push element into array
        //$concat=(strpos($match[1],'(Co)')!==0?true:false);
        If (substr($row, 0, 5) == '(Co) ') {   
            $row_previous=true;
        }

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Este é o código Guilherme,

 

while(!feof($file)){
    $row=trim(fgets($file,1024));
    
    if(preg_match('/^\(Cd\)\s(.+)/',$row,$match)){  // capture Cd numbers
        ++$i;  // increment outer_index
        $j=-1;  // reset inner_index
        $id=$match[1];  // store cd value
        //$concat=true;
        $row_previous=false;
        $row_ob=false;
       
    }elseif(preg_match('/^(\(..\)\s.*)/',$row,$match)){  // capture Cd data
        //if(isset($match)?$j:$j);
        ++$j;  // this is a new innerarray element, increment its index
        $cd[$i][$id][$j]=$match[1];  // push element into array
        If (substr($row, 0, 5) == '(Co) ') {   
            $row_previous=true;
        }
        
    }elseif(isset($id)){  
            
            If (($row_previous == true)&& ($row_ob !== true)){
            ++$j; //increment its index to insert variable value created for the additional lines
            $row="(Ob) ". (trim($row)); //create pre value variable
            $row_ob=true;
            $cd[$i][$id][$j].="$row ";  // concatenate to last element to new
        }else{ 
        $cd[$i][$id][$j].=" $row";  // concatenate to last element
        $row_previous=false;
        $row_ob=false;
        }
    }
 
}

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por eduardodsilvaq
      Não sei oq tem de errado.
       
      O erro:
      Notice: Undefined index: name in C:\AppServ\www\includes\functions.php on line 105 A linha do erro:
      <td width="106"><div class="fonte">'. $row["name"] .'</div></td> O codigo:
      function mini_ranking (){ $PDO = db_connect_gamedata(); $sql = "SELECT name baselevel FROM u_hero WHERE class <> '80' ORDER BY baselevel Desc Limit 6"; $result = $PDO->query($sql); $guild = $result->fetchAll(PDO::FETCH_ASSOC); $i = 1; echo '<table width="153" height="0" border="0">'; foreach($guild as $row) { echo '<tr> <td width="0" height="0" align="center"><div class="fonte">'. $i++ . '</div></td> <td width="106"><div class="fonte">'. $row["name"] .'</div></td> <td width="20"><div class="fonte">'. $row["baselevel"] .'</div></td> <tr>'; } echo '</table>'; }  
    • Por unset
      Olá a todos, tenho uma aplicação pequena, que roda normalmente no php5 porém ao mudar a versão do php para 7 a mesma está apresentando a seguinte mensagem de erro
       
      Notice: Trying to access array offset on value of type null in
       
       
      <?php /* * APP CORE CLASS * Creates URL & Loads Core Controller * URL Format - /controller/method/param1/param2 */ class Core { // Set Defaults protected $currentController = 'Pages'; // Default controller protected $currentMethod = 'index'; // Default method protected $params = []; // Set initial empty params array public function __construct(){ $url = $this->getUrl(); // Look in controllers folder for controller if(file_exists('../app/controllers/'.ucwords($url[0]).'.php')){ // If exists, set as controller $this->currentController = ucwords($url[0]); // Unset 0 index unset($url[0]); } // Require the current controller require_once('../app/controllers/' . $this->currentController . '.php'); // Instantiate the current controller $this->currentController = new $this->currentController; // Check if second part of url is set (method) if(isset($url[1])){ // Check if method/function exists in current controller class if(method_exists($this->currentController, $url[1])){ // Set current method if it exsists $this->currentMethod = $url[1]; // Unset 1 index unset($url[1]); } } // Get params - Any values left over in url are params $this->params = $url ? array_values($url) : []; // Call a callback with an array of parameters call_user_func_array([$this->currentController, $this->currentMethod], $this->params); } // Construct URL From $_GET['url'] public function getUrl(){ if(isset($_GET['url'])){ $url = rtrim($_GET['url'], '/'); $url = filter_var($url, FILTER_SANITIZE_URL); $url = explode('/', $url); return $url; } } }  
      Alguém poderia dar uma força ai?
    • Por Antena
      Olá pessoal, 
      Estou com um problema , onde o script não está possibilitando a inserção de novos dados desde o dia 02/09. O erro apresentado é este:
       
      02-Sep-2019 13:11:18 America/Fortaleza] PHP Notice: Uninitialized string offset: 17 in /home/xxx/xxx/site/config/func.php on line 30 A parte da função que apresenta este problema é este:
       
      function remove_extra_in_url($url) { $extra=array('https://','http://','www.',' '); $url=strtolower($url); $url=str_replace($extra,'',$url); $i=0; $site_name=''; $len=strlen($url); while($url[$i]!='/' && $url[$i]!='?' && $i<$len) { $site_name.=$url[$i]; $i++; } return $site_name; } Mais especificamente esta linha:
       
      while($url[$i]!='/' && $url[$i]!='?' && $i<$len)  
       
      Alguém poderia me ajudar?
    • Por carlosmoises
      Olá Pessoal!
       
    • Por fael97
      Ola pessoa descupem-me pelo título mas tive que faze-lo.
      é o seguinte estou ficando louco com um bug que está me ocorrendo e não sei resolve-lo.
       
      bem, tenho uma tabela chamada conexões, nela tenho os campos (familia_um,familia_dois,ativo) e tenho outra tabela chamada familia com varios campos.
      quero fazer  assim, buscar todas as famílias  na base e filtrar as conexões de uma determinada família. Se existe conexão entre a família x e y em conexões [familia_um = x e familia_dois = y], eu não vou pegar a família y(a família que está na tabela familias), ou seja quero pegar a família que não está em conexão com com as famílias de uma determinada família, acho que entenderam.
       
      já fiz assim, criei um vetor chamado conexoes_array que guardará todas as famílias para que possa ser filtrado.
      criei outro chamado familia_array que guarda as minhas conexões, ou seja cada família possui conexões na base como se fosse uma rede
      agora tenho que verificar 
       
      agora está desenvolvendo mais, quero pegar a família de conexoes_array(a,c,e) que não está entre minhas conexões em familia_array(a,b,c,d,e), por tanto fiz assim
      criei uma array chamado nova_conexao
       
      Mas está aparecendo o seguinte erro, e assim por diante para outras chaves.....
      ( ! ) Notice: Undefined index: idfamilia in D:\wamp64\www\onfamily.com\nav\conexoes\sistema\busca_conexoes.php on line 110 Call Stack # Time Memory Function Location 1 0.0000 402080 {main}( ) ...\busca_conexoes.php:0  
       
      Oque faço para resolver este erro, e se caso houver uma outra solução para este meu problema, podem me ajudar?
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.