1

I´m trying to insert arrays into other array, the problem is that when I call the array_push() method it overwrites the last one element of my array, then I just get an array with data of one array (the last one):

  $users_data = [];
    $resultSize = count($result); 

    $data = $result; 

    for ($i = 0; $i < $resultSize; $i++) {
        $person = [
            'nombre'         => $result[$i]['nombre'],
            'apellido'       => $result[$i]['apellido'],
        ];
        array_push($users_data, $person);
        // $users_data = $person; I also have tried with this method. 
    };

I just receive one object with this:

 Object {nombre: jane, apellido: doe}

What is going wrong?

2 Answers 2

3

It shud be like this,

$person['nombre'][$i] = $result[$i]['nombre'];
$person['apellido'][$i] = $result[$i]['apellido'];
                   ^ you have missed this index.

Then no need of array_push(). you can directly assign persons to user_data

Sign up to request clarification or add additional context in comments.

2 Comments

@LeonardoCavani consider accepting the answer if it was helpful.
I needed 8 minutes to do it XD. Thanks !
0

Or like this :

 for ($i = 0; $i < $resultSize; $i++) {
    $users_data['nombre'][] = $result[$i]['nombre'];
    $users_data['apellido'][] = $result[$i]['apellido'];
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.