First row in array php

Get first row of array php

Question: I have this while loop in php: Which out puts 12 rows, for example: .00%, .00%, .00%, .00%, 26.22%, .00%, 3.96%, 1.49%, 5.23%, 20.88%, 42.22%, .00% Is there a way to only print out 1 particular row? So you have to access the data using object notation.

Read first record of array instead of first character in Laravel

I’m using Laravel 8 . I’ve saved some array in my database and when I try to read those arrays I just get a single character of it.

For example the array in database is [«one», «two»] and when i write

it will just show ‘[‘ instead of ‘one’

in my migration file i did this :

$table->json('y'); and in my model i did this : protected $casts = [ 'y' => 'json', ]; 

and also in model i did try this :

 protected $casts = [ 'y' => 'array', ]; 

and in my controller i did something like this one to show data :

 public function showData()< $x = DB::select('select * from x'); return view('home',['x'=>$x]); > 

I’ve solved the problem. the problem was the way that i’ve called the record on table. I missed adding

Читайте также:  text-transform

to my controller. and in my controller i used to write

$x = DB::(select * from mytable); 

Get first and last element in array, current(): The current() function returns the value of the current element in an array. Every array has an internal pointer to its «current»

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 ) ) 
$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") 

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 . '
'; echo $last_record . '
'; echo '
'; print_r($new_array); echo '

';

Belo Horizonte, Minas Gerais Monte Mor, São Paulo Array ( [0] => Maricá, Rio de Janeiro ) 

First element of array by condition, Use array_filter to apply condition and take first value of filtered: array_values( array_filter( $input, function($e)< return $e[

Access one row in an array PHP

I have this while loop in php:

Which out puts 12 rows, for example:

.00%, .00%, .00%, .00%, 26.22%, .00%, 3.96%, 1.49 %, 5.23%, 20.88%, 42.22%, .00%

Is there a way to only print out 1 particular row?

I have tried things like this:

But because the the array returns a sting, I am getting the nth single character not the nth row of data. So instead of getting ‘26.22’ im am getting ‘2’

If it is returning a string you can convert it to an array and access it via its index. To convert a string to an array you can use the explode function.

$string = '.00%, .00%, .00%, .00%, 26.22%, .00%, 3.96%, 1.49%, 5.23%, 20.88%, 42.22%, .00%'; $result = explode(',' $string); $finalvalue = $result[0]; 

Note : The $result[0] will return the first value of the string, you will have to set the index which you require.

working with mysql I use that function:

function ExecuteQuery_assocArray($query) < $result = mysqli_query($this->link, $query); $set = array(); while ($set[] = mysqli_fetch_assoc($result)); return $set; > 

How to access first row of array and then access key and element, So I am working on WordPress + PHP, and I’ve used WordPress’s get_results with OBJECT_K parameter, which returns array. The output architecture

Источник

Как получить первый элемент массива в php

Итак, у нас есть массив $arr и нужно получить первый элемент этого массива.

Нельзя просто сделать так:

Элемент с индексом 0 может быть просто не определен. Например в случае если массив ассоциативный, либо мы сделали unset($arr[0]) .

Способ 1

Используя reset мы получаем первый элемент, однако есть один побочный эффект: указатель массива также сбрасывается на первый элемент. Хотя в принципе эта функция и предназначена для сброса указателя. Документация по функции reset().

Обратите внимание: если массив пустой reset() вернет false , и этот результат будет неотличим от случая, когда массив не пустой, но содержит false в качестве первого элемента.

$a = array(); $b = array(false, true, true); var_dump(reset($a) === reset($b)); //bool(true)

Способ 2

Можно воспользоваться функцией array_shift — она извлекает первый элемент и при этом удаляет его из переданного массива. Документация по array_shift().

Способ 3

Написать свою функцию для этих целей:

function array_first($array, $default = null) < foreach ($array as $item) < return $item; >return $default; >

Преимущество в том, что она не меняет исходный массив. Также вы можете передать параметр $default , который будет использоваться в качестве значения по умолчанию, если массив пустой.

Кстати во фреймворке Laravel эта функция уже определена и позволяет указать еще и callback, в который можно передать условие. Можно например взять первый элемент, который больше 10 или первый элемент, который не является числом.

Вот код более совершенной функции:

function array_first($array, callable $callback = null, $default = null) if (is_null($callback)) < if (empty($array)) < return $default instanceof Closure ? $default() : $default; >foreach ($array as $item) < return $item; >> foreach ($array as $key => $value) < if (call_user_func($callback, $value, $key)) < return $value; >> return $default instanceof Closure ? $default() : $default; >

Ее можно использовать например так:

$array = [100, 200, 300]; $first = array_first($array, function ($value, $key) < return $value >= 150; >); echo $first; // 200

Способ 4

Функция current() также пригодна для получения первого элемента массива.
Пример использования:

$transport = array('foot', 'bike', 'car', 'plane'); $mode = current($transport); // $mode = 'foot';

Точнее эта функция используется для возвращения элемента, на котором находится внутренний указатель массива. В большинстве случаев указатель на первом элементе, однако есть ситуации, когда может быть возвращен не первый элемент.

$transport = array('foot', 'bike', 'car', 'plane'); next($transport); // перемещаем указатель вперед (http://php.net/manual/ru/function.next.php) $mode = current($transport); // $mode = 'bike'; — т. е. вернулся уже второй элемент массива.

Спасибо комментатору Alexey Berlinskiy, за этот способ.

Если вы еще знаете способы получения первого элемента — пишите в комментариях.

Источник

Php get first row of array php

Output: Solution 3: Because you don’t use value of $settings[‘items’] in the code, you can just work with that array length Solution 1: It seems like is getting cached with last statement. You probably write instead of Other possibilities can be violation of any constraints, you might have unique key constraints on any of the column and trying to insert same value within the loop.

Displaying php array in three column, first row one element and second and third row two element

$first = true; $all = []; $couples = []; foreach ($settings['items'] as $item)< if($first)< $first = false; $first_out = 'First'; //or whatever $all[] = $first_out; >else < if(count($couples) == 2)< $all[] = $couples; $couples = []; >$couples[] = 'Second'; > > foreach($all as $value)< echo '
'; >

A little pre-wrangling, remove the first item, and then merge it into the remaining chunked array.

array(3) < [0]=>array(1) < [0]=>string(3) "foo" > [1]=> array(2) < [0]=>string(3) "foo" [1]=> string(3) "foo" > [2]=> array(2) < [0]=>string(3) "foo" [1]=> string(3) "foo" > > 

Because you don’t use value of $settings[‘items’] in the code, you can just work with that array length

$count = count($settings['items']); if ($count--) echo ` 
1) < echo '
'; $count -= 2; > if ($count--) echo `

Only first row data is inserted while using multiple array

It seems like prepare is getting cached with last statement. You probably write

$sql = "INSERT INTO mark(subjectid, theory, practical, stdname) VALUES (:subjectid, :theory, :practical, :stdname)"; $query = $con->prepare($sql); foreach ($theory AS $key => $item)  
foreach ($theory AS $key => $item) < $sql = "INSERT INTO mark(subjectid, theory, practical, stdname) VALUES (:subjectid, :theory, :practical, :stdname)"; $query = $con->prepare($sql); 

Other possibilities can be violation of any constraints, you might have unique key constraints on any of the column and trying to insert same value within the loop. You can verify by adding below line of code to your code.

Use of Nested foreach works

foreach ($stdname AS $key => $item)< $query->bindParam(':stdname', $stdname[$key]); foreach ($theory AS $key => $item) < $query->bindParam(':subjectid', $subjectid[$key]); $query->bindParam(':theory', $theory[$key]); $query->bindParam(':practical', $practical[$key]); $query->execute(); > > 

How to access first row of array and then access key and element, So I am working on WordPress + PHP, and I've used WordPress's get_results with OBJECT_K parameter, which returns array. The output architecture

Mysql query don't get first row in PHP [duplicate]

You fetch the first row already before the while loop starts.

 $row = $result->fetch_assoc(); // fetch_assoc()) 

Making this call moves the result pointer up but you're not adding this row to $ordersArray .

Alternatively, if for some reason you do need to access the first row outside your while loop, either add the data to the new array or use $result->data_seek(0) to reset the pointer.

Load a array from CSV using php and index first row and first column,

Access one row in an array PHP

If it is returning a string you can convert it to an array and access it via its index. To convert a string to an array you can use the explode function.

$string = '.00%, .00%, .00%, .00%, 26.22%, .00%, 3.96%, 1.49%, 5.23%, 20.88%, 42.22%, .00%'; $result = explode(',' $string); $finalvalue = $result[0]; 

Note : The $result[0] will return the first value of the string, you will have to set the index which you require.

working with mysql I use that function:

function ExecuteQuery_assocArray($query) < $result = mysqli_query($this->link, $query); $set = array(); while ($set[] = mysqli_fetch_assoc($result)); return $set; > 

Div array from mysqli database not showing first row, because you already have a $row = $result->fetch_assoc(); in the beginning (line 3), thus skip the first row. – Jeff

Источник

How to Get the First Element of an Array in PHP

If you know the exact index or key of an array you can easily get the first element, like this:

Example

 "Apple", "b" => "Ball", "c" => "Cat"); echo $fruits["a"]; // Outputs: Apple ?>

However, there are certain situations where you don't know the exact index or key of the first element. In that case you can use the array_values() function which returns all the values from the array and indexes the array numerically, as shown in the following example:

Example

 "Apple", 5 => "Ball", 11 => "Cat"); echo array_values($arr)[0]; // Outputs: Apple ?>

Alternativly, you can also use the reset() function to get the first element.

The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.

You can also use the current() function to get the first element of an array. This function returns the current element in an array, which is the first element by default unless you've re-positioned the array pointer, otherwise use the reset() function. Here's an example:

Example

 "Apple", 5 => "Ball", 11 => "Cat"); echo current($arr); // Outputs: Apple echo reset($arr); // Outputs: Apple echo next($arr); // Outputs: Ball echo current($arr); // Outputs: Ball echo reset($arr); // Outputs: Apple ?>

Here are some more FAQ related to this topic:

Источник

Оцените статью