Php массив удалить индексы

Как убрать индексы из массива в php?

Я уже использую функции PHP basename а также array_shift , но они не дали мне надлежащую ценность. Я хочу только одну строку COUNT(ID) значение.

Вот моя функция, используемая в модели CakePHP:

$res = $this->query("select COUNT(ID) from users where Username = '".$Username['Username']."'"); if ($res[0][0]['COUNT(ID)'] >= 1) < return false; >else

Мне не нужно $res[0][0] Мне нужно только COUNT[ID] , Есть ли простой способ найти только COUNT[ID] ,

8 ответов

Если вы используете CakePHP, хорошо бы использовать модель и встроенные функции, чтобы получить ответ, что вы хотите.

$this->loadModel('User'); //If you are in controller $total = $this->User->find('count', array( 'conditions' => array('Username' => $Username['Username']) )); 

Вы получите ответ в одной переменной.

Допустим, имя вашего массива $myArray чем вы можете присвоить значение $myArray[0][0][‘COUNT(ID)’] в $value так, как вы обычно назначаете значение: $value = $myArray[0][0][‘COUNT(ID)’]; ,

Если вы хотите удалить индекс из массива, используйте unset() как это: unset($myArray[0][0][‘COUNT(ID)’]) , Надеюсь, это ответит на ваш вопрос.

Если вы уверены, что структура массива останется прежней, это может быть полезно:

function array_values_recursive($ary) < $lst = array(); foreach( array_keys($ary) as $k )< $v = $ary[$k]; if (is_scalar($v)) < $lst[] = $v; >elseif (is_array($v)) < $lst = array_merge( $lst, array_values_recursive($v) ); >> return $lst; > $arr=array(array(array('COUNT(ID)'=>5))); $res=array_values_recursive($arr); echo '
';print_r($res); 

Вы можете получить его по ассоциативному массиву, чтобы уменьшить размерность, но вы можете удалить индекс. Может быть, вы можете использовать foreach для автоматического использования индексов.

public $uses = array('User'); $count = $this->User->find('count', array( 'conditions' => array('Username' => $Username['Username']) )); if ($count >= 1) < return false; >else

Если вы знаете точное число вложений в массиве, вы можете просто получить к нему доступ с помощью индексов.

Если нет, вы можете использовать функцию, которая рекурсивно найдет первый вложенный элемент, который не является массивом

function getStringFromArray($array) < if (is_array($array)) < foreach ($array as $key =>$value) < if (is_array($value)) < return getStringFromArray($value); >else < return $value; >> > else < throw new Exception("Not an array given"); >> 

Ваш вывод производится с помощью кода, подобного этому

$data = array( array( array( 'COUNT(ID)' => 0 ) ) ); 

Вы можете получить доступ к его значению, позвонив напрямую

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

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

$arr = Set::extract("/0/COUNT(ID)",$data); 

где $data - ваш входной массив.

вы получите следующий вывод

Вы можете обратиться по ссылке ниже

Источник

Как удалить индексы из массива php

В PHP удаление индекса массива равнозначно удалению элемента с этим индексом из массива.

$numbers = [1, 2, 3, 4, 5]; unset($numbers[2]); print_r($numbers); # => Array # => ( # => [0] => 1 # => [1] => 2 # => [3] => 4 # => [4] => 5 # => ) 

Функция unset() удалит из массива указанный индекс (2), в результате изменит исходный массив.

Источник

Как удалить индексы из массива?

Добрый день!
Имеется массив
Array ( [0] => 14, [1] => 15, [2] => 12 )
Как его привести к виду array(14, 15, 12) ?

Простой 3 комментария

sayber

У массива по умолчанию есть индексы.
[14, 15, 12]

Это и есть
[0 => 14, 1 => 15, 2 => 12]
и язык не важен

Особенно нравится - full stack developer, опыт работы более 7 лет

да ладно) Бывает тяжелая неделя была, голова дымится и уже так тупишь, что джуны про тебя думаю "Ты чо несешь вообще, какие индексы?"

iNickolay

Массив (в некоторых языках программирования также таблица, ряд, матрица) — тип или структура данных в виде набора компонентов (элементов массива), расположенных в памяти непосредственно друг за другом. При этом доступ к отдельным элементам массива осуществляется с помощью индексации, то есть через ссылку на массив с указанием номера (индекса) нужного элемента. За счёт этого, в отличие от списка, массив является структурой данных, пригодной для осуществления произвольного доступа к её ячейкам

Ну а если коротко, то массив
array(14, 15, 12)
это и есть массив
array([0] => 14, [1] => 15, [2] => 12)

М-да. Массивы говорите одинаковые? А если так?

$a1=array(14, 15, 12);
$a2=array([0] => 14, [1] => 15, [2] => 12);
echo in_array(14, $a1);
echo in_array(14, $a2);

Источник

Php массив удалить индексы

// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4

Used to creating arrays like this in Perl?

Looks like we need the range() function in PHP:

$array = array_merge (array( 'All' ), range ( 'A' , 'Z' ));
?>

You don't need to array_merge if it's just one range:

There is another kind of array (php>= 5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=['string1'=>$data1, 'string2'=>$data2 etc. ]

when getting the keyed data with

php does *not* have to search through the array comparing each key string to the given key ('string1') one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it's all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It's also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).

When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = ['bebe' => 'Bob', 'age' => 23, 'too' => 23 ];
xdebug_debug_zval( 'arr' );

(refcount=2, is_ref=0)
array (size=3)
'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
'age' => (refcount=0, is_ref=0)int 23
'too' => (refcount=0, is_ref=0)int 23

but :
$arr = ['bebe' => 'Bob', 'age' => 23, 'too' => '23' ];
xdebug_debug_zval( 'arr' );

(refcount=2, is_ref=0)
array (size=3)
'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
'age' => (refcount=0, is_ref=0)int 23
'too' => (refcount=1, is_ref=0)string '23' (length=2)
or :

$arr = ['bebe' => 'Bob', 'age' => [1,2], 'too' => [1,2] ];
xdebug_debug_zval( 'arr' );

(refcount=2, is_ref=0)
array (size=3)
'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
'age' => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
'too' => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2

This function makes (assoc.) array creation much easier:

function arr (. $array )< return $array ; >
?>

It allows for short syntax like:

$arr = arr ( x : 1 , y : 2 , z : 3 );
?>

Instead of:

$arr = [ "x" => 1 , "y" => 2 , "z" => 3 ];
// or
$arr2 = array( "x" => 1 , "y" => 2 , "z" => 3 );
?>

Sadly PHP 8.2 doesn't support this named arguments in the "array" function/language construct.

Источник

Читайте также:  Java stderr to file
Оцените статью