Foros del Web » Programando para Internet » PHP »

Array de objetos dentro de Array de objetos

Estas en el tema de Array de objetos dentro de Array de objetos en el foro de PHP en Foros del Web. hola, Vuelvo con una duda xD, he echo lo siguiente. Código: private function loadTasks() { // load all tasks of the project $bd = $_SESSION['bd']; ...
  #1 (permalink)  
Antiguo 06/06/2011, 13:01
 
Fecha de Ingreso: junio-2010
Mensajes: 353
Antigüedad: 13 años, 10 meses
Puntos: 6
Array de objetos dentro de Array de objetos

hola,
Vuelvo con una duda xD, he echo lo siguiente.

Código:
private function loadTasks() {
        // load all tasks of the project
        $bd = $_SESSION['bd'];
        $opcion = "ObjdeMysql";
        $dataset = $bd->loadMainTasks($this->projectId);

        while ($registro = mysql_fetch_array($dataset)) {
                $nombresString = $this->nombreString($registro['taskid'], $bd);

                $TaskClass = new TaskClass($opcion, $registro['taskid'], $registro['parentid'], $registro['name'], $registro['initialdate'], $registro['enddate'], $registro['desc'], $nombresString,$this->childs[]=($this-> loadChildTasks($registro['taskid'])));
                $this->tasks[] = $TaskClass;
        
        }
    }

private function loadChildTasks($parentId) {
      $opcion = "ObjdeMysql";
      $bd = $_SESSION['bd'];
       $dataset = $bd->loadTask($parentId,$this->projectId);
       while ($registro = mysql_fetch_array($dataset)) {
      $nombresString = $this->nombreString($registro['taskid'], $bd);
      $TaskClass = new TaskClass($opcion, $registro['taskid'], $registro['parentid'], $registro['name'], $registro['initialdate'], $registro['enddate'], $registro['desc'], $nombresString,$this->childs[]=($this-> loadChildTasks()));
      $this->childs[] = $TaskClass;
      return $this->childs;
       }
}
Como accedo al array de childs atraves de la array del padre?

tenggo metodos de get de todas las cosas en cada clase i ProjectClass hereda de TaskClass.

Osea tengo control desde ProjectClass para crear un array de objetos de task con otra array de objetos task(que serian los hijos que estos tienen hijos etc.. en funcion de lo que tengo en la bd de mysql)
  #2 (permalink)  
Antiguo 06/06/2011, 13:05
Avatar de memoadian
Colaborador
 
Fecha de Ingreso: junio-2009
Ubicación: <?php echo 'México'?>
Mensajes: 3.696
Antigüedad: 14 años, 10 meses
Puntos: 641
Respuesta: Array de objetos dentro de Array de objetos

bueno eso de los hijos me suena a javascript, desconozoco si se usa con php disculpenme si sueno muy sonzo, pero que no en un array común acceder a un sub array es asi?

$a[1][3] por ejemplo.
  #3 (permalink)  
Antiguo 06/06/2011, 13:36
 
Fecha de Ingreso: junio-2010
Mensajes: 353
Antigüedad: 13 años, 10 meses
Puntos: 6
Respuesta: Array de objetos dentro de Array de objetos

hola,

Es php, sí es eso pero en php no sé si puedo lo probaré


Estado mirando arrays de php , he cambiado el sistema y ahora hago esto;

$this->tasks[] = array("padre" =>$TaskClass , "hijas" =>$arrayHijas)

Pero en php puedo hacer..

this->task[0] ["padre"]->getETC();
y
this->task[0] ["hija"]->$arrayHijas[0]->getETC();


?? ó tengo que usar otro manera?
  #4 (permalink)  
Antiguo 06/06/2011, 13:49
 
Fecha de Ingreso: junio-2010
Mensajes: 353
Antigüedad: 13 años, 10 meses
Puntos: 6
Respuesta: Array de objetos dentro de Array de objetos

me dice lo siguiente :S,

Fatal error: Cannot use object of type TaskClass as array in E:\EasyPHP-5.3.6.0\www\Exam\pages\homepageC2.php on line 68


Clase;
$this->tasks[] = array($TaskClass ,$this->loadChildTasks($registro['taskid']));

Controlador;
$PoorChilds = $ProjectClass->getArrayOfTask();
$PoorChilds [0][2]->getName()


Vale pero como lo hago sino ? xD he probado varias cosas y todas acaban en lo mismo voy a cenar
  #5 (permalink)  
Antiguo 06/06/2011, 13:59
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Array de objetos dentro de Array de objetos

Porque has cambiado el sistema ?, antes estaba bien, si quieres acceder al parent, deberías tener una relación bidireccional guardando en una propiedad el parent.

El error es claro intentas acceder a un objeto como array, getArrayOfTask te esta devolviendo un objeto no un array, aunque puedes implementar ArrayAccess para poder tratar como array a TaskClass.

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)
  #6 (permalink)  
Antiguo 06/06/2011, 14:27
 
Fecha de Ingreso: junio-2010
Mensajes: 353
Antigüedad: 13 años, 10 meses
Puntos: 6
Respuesta: Array de objetos dentro de Array de objetos

para que me sea más simple acceder no sé xd, pero llevas razón.

Bueno, de la manera antigua como puedo dibujar?

TaskClass($opcion, $registro['taskid'], $registro['parentid'], $registro['name'], $registro['initialdate'], $registro['enddate'], $registro['desc'], $nombresString,$this->childs[]=($this-> loadChildTasks($registro['taskid'])))

No se supone que haciéndo;

$PoorChilds = $ProjectClass->getArrayOfTask();
$Childs = $PoorChilds[0]->getArrayOfChilds();

$Childs es igual a $PoorChilds[0]->Array de Childs?

Entonces prk me dice, al hacer ; $Childs[0]->getName()
Call to a member function getName() on a non-object in

Si el array de objetos de childs(que obtengo al llamar al get) es un obj al hacer $childs[0]

Encambio puedo hacer esto; :S

$PoorChilds = $ProjectClass->getArrayOfTask();
$PoorChilds[0]->getName();

Se me olvidava comentar que hago esto; No sé si podría influir en algo :s
$ProjectClass = $_SESSION["ProjectClass"];

creado después de hacer el login i usando el mismo todo el rato

Última edición por marcwolf; 06/06/2011 a las 14:36
  #7 (permalink)  
Antiguo 06/06/2011, 14:52
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Array de objetos dentro de Array de objetos

Habría que ver la implementacion que tienes, para comprobar los datos debugealos, hace un var_dump y checka el tipo de datos para ver porque falla.

Te estas mareando mas de la cuenta, no es mas que una estructura jerárquica, son en definitiva nodos anidados.

Postea el código y utiliza el syntax highlighter así es mas fácil de leer.
__________________
http://es.phptherightway.com/
thats us riders :)
  #8 (permalink)  
Antiguo 06/06/2011, 15:06
 
Fecha de Ingreso: junio-2010
Mensajes: 353
Antigüedad: 13 años, 10 meses
Puntos: 6
Respuesta: Array de objetos dentro de Array de objetos

Ahí va, hay metodos no-terminados no le hagas caso prk no lo uso demomento.
ProjectClass
Código PHP:
<?php

include_once "./clases/TaskClass.php";
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ProjectClass
 *
 * @author marc
 */
class ProjectClass extends TaskClass {

    private 
$groupId;
    private 
$name;
    private 
$projectId;
    private 
$tasks = array(); //array of main tasks
    
private $numChilds 0;
    private 
$projects = array(); // array de projects

    
public function __construct($opcion$var1$var2) {
        if (
$opcion == "CreariDProject") {
            
$this->CreariDProject($var1);
            
$this->loadTasks();
        }
        if (
$opcion == "Load") {

            
$this->loadProjects();
        }
    }

    public function 
CreariDProject($var1) {
        
$this->projectId $var1;
    }

    public function 
CrearProject($var1) {
        
$this->name $var1;
    }

    public function 
Asignar($var1$var2) {
        
$this->projectId $var1;
        
$this->groupId $var2;
    }

    public function 
getProjectId() {
        return 
$this->projectId;
    }

    public function 
getGroupId() {
        return 
$this->groupId;
    }

    public function 
loadProjects() {
        
$bd = ($_SESSION['bd']);
        
$PersonClass $_SESSION['PersonClass'];
        
$dataset $bd->getListProjects($PersonClass->getGroupId());
        
$i 0;
        while (
$registro mysql_fetch_array($dataset)) {
            
//projectid     groupid     name
            
$this->projects[$i] = ($registro['projectid']);
            
$i++;
            
$this->projects[$i] = ($registro['name']);
            
$i++;
            if (!isset(
$this->projects[$i])) {

                
$this->projects[$i] = ("");
                
$i++; //CampoReservado:user
                
$this->projects[$i] = ("");
                
$i++; //CampoReservado:IP
            
}
        }
        return 
$i;
    }

    public function 
markProject($projectID$userID$IP) {
        
//selects a project for modification by a user with an ip address
        // throws an error if the project had been selected before.
        
for ($i 0$i count($this->projects); $i++) {
            if (
$projectID == $this->projects[$i]) {

                
$this->projects[$i 2] = $userID;
                
$this->projects[$i 3] = $IP;
            }
        }
    }

    public function 
unMarkProject($projectID) {
        
// unselects a project that has previously modified
        // throws an error if the project hadn't been selected
    
}

    function 
getArrayOfProjects() {
        return 
$this->projects;
    }

    public function 
getArrayOfTask() {
        return 
$this->tasks;
    }
 public function 
getArrayOfTask2($i) {
        return 
$this->tasks[$i]->getArrayOfChilds();
    }


    
//$taskId,$parentId, $name, $iniDate, $endDate, $desc
    
public function createMainTask($opcion$taskId$parentId$name$iniDate$endDate$desc$nombresString) {
        
// create a new object(rojectid(atuomatico)     taskid     name     initialdate     enddate     desc     parentid(asignar))
        // Tengo que contar las task para añadirle un taskId, para el controlo de estas
        
$bd $_SESSION['bd'];

        
$TaskClass = new TaskClass($opcion$taskId$parentId$name$iniDate$endDate$desc$nombresString);
        
$this->tasks[] = $TaskClass;
    }

    function 
addChild($opcion$taskId$parentId$name$iniDate$endDate$desc$nombresString) {
        
//adds a subtask
        // Tengo que contar las task para añadirle un taskId, para el controlo de estas
        
$bd $_SESSION['bd'];

        
//Tareasaddchild 0,$_SESSION['taskId'], $_POST['name'], $_POST['iniDate'], $_POST['endDate'], $_POST['desc']
        //addchild $taskId,$parentId, $name, $iniDate, $endDate, $desc
        //

        
$TaskClass = new TaskClass($opcion$taskId$parentId$name$iniDate$endDate$desc$nombresString);
        
$this->childs[] = $TaskClass;
    }
private function 
loadTasks() {
        
// load all tasks of the project
        
$bd $_SESSION['bd'];
        
$opcion "ObjdeMysql";
        
$dataset $bd->loadMainTasks($this->projectId);

        while (
$registro mysql_fetch_array($dataset)) {
                
$nombresString $this->nombreString($registro['taskid'], $bd);

                
$TaskClass = new TaskClass($opcion$registro['taskid'], $registro['parentid'], $registro['name'], $registro['initialdate'], $registro['enddate'], $registro['desc'], $nombresString,$this->childs[]=($this-> loadChildTasks($registro['taskid'])));
                
$this->tasks[] = $TaskClass;

        }
    }

private function 
loadChildTasks($parentId) {
      
$opcion "ObjdeMysql";
      
$bd $_SESSION['bd'];
       
$dataset $bd->loadTask($parentId,$this->projectId);
       while (
$registro mysql_fetch_array($dataset)) {
      
$nombresString $this->nombreString($registro['taskid'], $bd);
      
$TaskClass = new TaskClass($opcion$registro['taskid'], $registro['parentid'], $registro['name'], $registro['initialdate'], $registro['enddate'], $registro['desc'], $nombresString,$this->childs[]=($this-> loadChildTasks()));
      
$this->childs[] = $TaskClass;
      return 
$this->childs;
       }
}

    function 
nombreString($taskid$bd) {
        
//Saco array de personid
        
$arrayPersonId $bd->countIdOfWorkers($taskid);
        
// Saco array de nombres ,concateno en un String y lo envio.
        
$nombresString $bd->nameWorkers($arrayPersonId);
        return 
$nombresString;
    }

    public function 
deleteTask($taskId) {
        
// only mark for remove the task selected.
        // if the task has childs then, are direct sons of his grandfather.
    
}

    public function 
deleteBranch($taskId) {
        
// mark for remove the task selected and all of his sons
    
}
    
 

}

?>
TaskClass

Código PHP:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of TaskClass
 *
 * @author marc
 */
class TaskClass {

    private 
$hasChanged// notify if the task has been change
    
private $deleted// notify if the task has been removed
    
private $childsDeleted//notify if the task has been removed so has been his children
    //put your properties here, ex: childs, inidate, endate...
    //projectid     taskid     name     initialdate     enddate     desc     parentid
    
private $taskId;
    private 
$name;
    private 
$iniDate;
    private 
$endDate;
    private 
$desc;
    private 
$parentId;
    private 
$childs = array(); // Array de hijos
    
private $nombresString// Array de hijos
    
private $padreId;
    private 
$opcion;

    function 
__construct($opcion$taskId$parentId$name$iniDate$endDate$desc$nombresString,$childs) {
        
$this->taskId $taskId;
        
$this->parentId $parentId;
        
$this->name $name;
        
$this->iniDate $iniDate;
        
$this->endDate $endDate;
        
$this->desc $desc;
        
$this->nombresString $nombresString;
        
$this->opcion $opcion;
        
$this->childs $childs;
    }

    function 
addWorker($userId) {
        
// workers MUST be users that belongs to groupId 
    
}

    function 
deleteWorker($userId) {
        
// delete a worker from that task
    
}

    function 
save() {
        
//save this object and his workers to BD throught BDController
        //and save all childs
        //if one task is mark for erased, then must be erase from BD
    
}

    
/** Getters
     * $parentId,$name, $iniDate, $endDate, $desc
     * */
        
function getArrayOfChilds() {
        return 
$this->childs;
    }
    public function 
getOpcion() {
        return 
$this->opcion;
    }

    public function 
getTaskId() {
        return 
$this->taskId;
    }

    public function 
getParentId() {
        return 
$this->parentId;
    }

    public function 
getName() {
        return 
$this->name;
    }

    public function 
getIniDate() {
        return 
$this->iniDate;
    }

    public function 
getEndDate() {
        return 
$this->endDate;
    }

    public function 
getDesc() {
        return 
$this->desc;
    }

    function 
getNameWorkers() {

        return 
$this->nombresString;
    }

    function 
getChild($taskId) {
        
//return (could be a direct or non direct child)
    
}

    function 
removeAll() {
        
//remove all task includes himself
        //$this->numChilds=0;
        
return numChilds;
    }

}

?>

BD Controller
: todos los metodos que tengan k ver con consultas/Inserts/etc en bd estan aquí
Código PHP:
Es demasiado largo XDpongo los métodos que uso,los del metodo para sacar string de workers no los he puesto

 
public function loadMainTasks($projectId){
        
// returns a list of task that belongs to the project and has no parents.
         
$consulta "SELECT * FROM `task` where projectid ='".$projectId."' and parentid='0';";
        
$dataset mysql_query($consulta,$this->link);
        return (
$dataset);
    }

    public function 
loadTask($parentId,$projectId){
        
// devolver una lista de tareas que pertenecen al proyecto identificado por projectId y su padre es parentID;
        
$consulta "SELECT * FROM `task` where projectid ='".$projectId."'and parentid='".$parentId."';";
        
$dataset mysql_query($consulta,$this->link);
        return (
$dataset);
    } 
Depués creo obj "ProjectClass" en login, y lo paso a SESSION["ProjectClass"]; y hago más cosas pero no influyen para este apartado

Última edición por marcwolf; 06/06/2011 a las 15:28

Etiquetas: objetos
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 15:08.