2

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")
3
  • 1
    This is not a multidimensional array. This is an array of objects. Commented Sep 20, 2018 at 1:26
  • 1
    Please provide an example of the expected result. You question is not clear. Commented Sep 20, 2018 at 1:27
  • updated ... i need to get this results! Commented Sep 20, 2018 at 1:36

1 Answer 1

1

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your solution .. but your explication was great .. thanks teacher!
No problem, good luck with the rest of your project. Cheers!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.