Mina Magdy
Mina Magdy

Reputation: 141

object arrays get the first and last record and create new array for who is between

How to get the first and last record [endereco] in object array and who between this first and last in another new array in codeigniter.

Array ( 
[0] => stdClass Object ( [id_destino] => 483596 [id_tag] => 0 [endereco] => Belo Horizonte, Minas Gerais [sort] => 0 ) 
[1] => stdClass Object ( [id_destino] => 483596 [id_tag] => 1 [endereco] => Maricá, Rio de Janeiro [sort] => 1 ) 
[2] => stdClass Object ( [id_destino] => 483596 [id_tag] => 2 [endereco] => Monte Mor, São Paulo [sort] => 2 ) )

Expected result:

$first_record = [endereco][0]; // "Belo Horizonte, Minas Gerais"
$last_record =  [endereco][2]; //in this case will be "Monte Mor, São Paulo"
print_r($new_array); //in this case will just be an array("Maricá, Rio de Janeiro")

Upvotes: 2

Views: 237

Answers (1)

Joseph_J
Joseph_J

Reputation: 3669

Your data is an array of objects. So you have to access the data using object notation.

As an example: $object->property;

$array = Array (

'0' => (Object)array( 'id_destino' => 483596, 'id_tag' => 0, 'endereco' => 'Belo Horizonte, Minas Gerais', 'sort' => 0),
'1' => (Object)array( 'id_destino' => 483596, 'id_tag' => 1, 'endereco' => 'Maricá, Rio de Janeiro', 'sort' => 1),
'2' => (Object)array( 'id_destino' => 483596, 'id_tag' => 2, 'endereco' => 'Monte Mor, São Paulo', 'sort' => 2)

);

//Here we get the first element and access the object's property.
$first_record = $array[0]->endereco;

//Here we get the last element by counting the number of elements and then accessing the last element's object properties.
$last_record = $array[count($array) - 1]->endereco;


//Here we loop through your array and using the loop's indexes only iterate across 
//the middle of the array.  On each iteration we push the object's property into a new array.
for($i = 1; $i < count($array) - 1; $i++){

  $new_array[] = $array[$i]->endereco;

}

echo $first_record . '<br>';
echo $last_record . '<br>';
echo '<pre>';
print_r($new_array);
echo '</pre>';

This will output:

Belo Horizonte, Minas Gerais

Monte Mor, São Paulo

Array
(
    [0] => Maricá, Rio de Janeiro
)

Upvotes: 1

Related Questions