Php get all keys object

Get keys from object in PHP [duplicate]

Utilising array map to form a new array of filtered objects just because in my personal opinion it seems cleaner and finally extracted the other loop into its own function just to improve readability. Solution 1: Solution 2: I think this will workout Solution 3: You can access objects value by using in laravel, try this

Get keys from object in PHP [duplicate]

You can type cast the stdObject to an array and use array_keys :

var_dump(array_keys((array)$object)); 

Search value in array object in PHP, So, first looping through all the indices of the array using foreach() . foreach ($array as $key => $subarray) if (in_array

Find object keys that begin with one of the strings in an array

Construct a regexp pattern that matches all of the prefixes, and check each key against the regexp:

$pattern = "^(" . join("|", $prefixes) . ")"; foreach($data as $datakey => $obj) < foreach($data as $datakey =>$obj) < foreach($obj as $property =>$value) < if (preg_match($pattern, $property)) . >> 

This still requires two loops, but there is no redundancy; each object in your data is examined only once. If you were to find a way to loop over all the objects’ contents without two PHP loops, it will still take just as many steps. The code in your question looped over each object multiple times (once for each prefix), which is indeed redundant.

Читайте также:  Document

Not sure whether you’ll prefer this or not but;

$prefixes = ['a_', 'b_']; $filtered = array_map(function($object) use ($prefixes) < return unsetPrefixedProperties($object, $prefixes); >, $data); function unsetPrefixedProperties($object, $prefixes) < $regex = '/('. implode('|', $prefixes) .').+/'; foreach ($object as $key =>$value) < if (preg_match($regex, $key)) < unset($object->); > > return $object; > 

Similar to alexis basically using regex to match, removing the need to loop through your prefixes. Utilising array map to form a new array of filtered objects just because in my personal opinion it seems cleaner and finally extracted the other loop into its own function just to improve readability.

Still not perfect, but it’s a start.

$matchedKeys = []; foreach ($data as $key => $value) < foreach ($prefixes as $val) < $length = strlen($val); if (substr($key, 0, $length) === $val) < $matchedKeys[] = $key; >> > The $matchedKeys array will hold the matching keys from object $data. 

PHP print keys from an object?, To display only the keys from an object, use array_keys() in PHP. Example. Live Demo

Decode Json And Getting All Value With Some Specific Key oR Object php

You want to find all subarrays which contain an element with a certain key and a certain value. In the general case, the level of the subarray is also not known, and neither is a path via specific keys. Recursive iterators are ideal for such tasks.

I have a universal filter function for the search.

/** * Returns all filtered elements including arrays as a new numeric key * * @param $arr array * @param $filter callable * @return array */ function arrayFilterRecursive(array $arr, $filter) < if(! is_callable($filter)) return false; $res = array(); $it = new RecursiveIteratorIterator( new RecursiveArrayIterator($arr),RecursiveIteratorIterator::SELF_FIRST ); foreach($it as $key =>$current) < if($filter($current, $key, $it)) < $res[] = $current; >> return $res; > 

A filter function is required for the special task here.

$key = 'player_id'; $value = 46139; $filter = function($current) use($key, $value)< return is_array($current) && isset($current[$key]) && $current[$key] == $value; >; 

Now only the Json string has to be converted into an array and our function has to be called.

$arr = json_decode($json,true); $result = arrayFilterRecursive($arr, $filter); 

The result for the selected example is an array:

array ( 0 => array ( 'bowl_type' => "Right-arm medium", 'image' => "https://example.com", 'country' => "South Africa", 'player_pos' => 7, 'total_points' => 109.0, 'selected_as_vccaption' => 1.6, 'team_id' => 150, 'selected_as_trump' => 0.0, 'points' => 12.0, 'playing_squad_updated' => "Y", 'selected_as_caption' => 0.64, 'is_in_substitute_squad' => "N", 'player_id' => 46139, 'credits' => 9.0, 'dob' => NULL, 'bat_type' => "Right-hand bat", 'name' => "T Bavuma", 'player_multiplier' => 1.0, 'position' => "batsman", 'is_in_playing_squad' => "Y", 'selected_by' => 45.1, ), ) 

The filter function can easily be adapted for other tasks. With

$key = 'player_id'; $filter = function($current) use($key)< return is_array($current) && isset($current[$key]) ; >; 

I get all sub-arrays that have a key ‘player_id’.

Searching for key in multidimensional array in PHP?, key and value have special meaning in arrays. What do you mean exactly when you say, ‘I would like to check if there is a value in this array

Obtain all keys x from an array of objects (php, laravel blade)

@foreach($item->orderedProducts as $op)  @if ('Extras' == $op->extra_type) extra_name >> 
@endif @endforeach

I think this will workout

@foreach($item->orderedProducts as $op) extras)) ?>   @foreach($array as $value) > @endforeach  @endforeach 

You can access objects value by using -> in laravel, try this

@foreach($item->orderedProducts as $op)  extra_name >>  @endforeach 

Get keys from object in PHP [duplicate], You can type cast the stdObject to an array and use array_keys : var_dump(array_keys((array)$object));.

Источник

array_keys

array_keys() returns the keys, numeric and string, from the array .

If a filter_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

Parameters

An array containing keys to return.

If specified, then only keys containing this value are returned.

Determines if strict comparison (===) should be used during the search.

Return Values

Returns an array of all the keys in array .

Examples

Example #1 array_keys() example

$array = array( 0 => 100 , «color» => «red» );
print_r ( array_keys ( $array ));

$array = array( «blue» , «red» , «green» , «blue» , «blue» );
print_r ( array_keys ( $array , «blue» ));

$array = array( «color» => array( «blue» , «red» , «green» ),
«size» => array( «small» , «medium» , «large» ));
print_r ( array_keys ( $array ));
?>

The above example will output:

Array ( [0] => 0 [1] => color ) Array ( [0] => 0 [1] => 3 [2] => 4 ) Array ( [0] => color [1] => size )

See Also

  • array_values() — Return all the values of an array
  • array_combine() — Creates an array by using one array for keys and another for its values
  • array_key_exists() — Checks if the given key or index exists in the array
  • array_search() — Searches the array for a given value and returns the first corresponding key if successful

User Contributed Notes 28 notes

It’s worth noting that if you have keys that are long integer, such as ‘329462291595’, they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.

$importantKeys = array( ‘329462291595’ => null , ‘ZZ291595’ => null );

foreach( array_keys ( $importantKeys ) as $key ) echo gettype ( $key ). «\n» ;
>

?>

will return on a 64 bits system:
integer
string
?>

but on a 32 bits system:
string
string
?>

I hope it will save someone the huge headache I had 🙂

Here’s how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:

$array = array( ‘first’ => ‘111’ , ‘second’ => ‘222’ , ‘third’ => ‘333’ );

// get the first key: returns ‘first’
print array_shift ( array_keys ( $array ));

// get the last key: returns ‘third’
print array_pop ( array_keys ( $array ));

// get the first value: returns ‘111’
print array_shift ( array_values ( $array ));

// get the last value: returns ‘333’
print array_pop ( array_values ( $array ));
?>

There’s a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.

Here’s a way to find all the keys from a multidimensional array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.

NOTE: If the sub element isn’t an array, it will be ignore.

function array_keys_recursive ( $myArray , $MAXDEPTH = INF , $depth = 0 , $arrayKeys = array()) if( $depth < $MAXDEPTH )$depth ++;
$keys = array_keys ( $myArray );
foreach( $keys as $key ) if( is_array ( $myArray [ $key ])) $arrayKeys [ $key ] = array_keys_recursive ( $myArray [ $key ], $MAXDEPTH , $depth );
>
>
>

return $arrayKeys ;
>
?>

EXAMPLE:
input:
array(
‘Player’ => array(
‘id’ => ‘4’,
‘state’ => ‘active’,
),
‘LevelSimulation’ => array(
‘id’ => ‘1’,
‘simulation_id’ => ‘1’,
‘level_id’ => ‘1’,
‘Level’ => array(
‘id’ => ‘1’,
‘city_id’ => ‘8’,
‘City’ => array(
‘id’ => ‘8’,
‘class’ => ‘home’,
)
)
),
‘User’ => array(
‘id’ => ’48’,
‘gender’ => ‘M’,
‘group’ => ‘user’,
‘username’ => ‘Hello’
)
)

output:
array(
‘Player’ => array(),
‘LevelSimulation’ => array(
‘Level’ => array(
‘City’ => array()
)
),
‘User’ => array()
)

It is worth noting that array_keys does not maintain the data-type of the keys when mapping them to a new array. This created an issue with in_array and doing a lookup on characters from a string. NOTE: my lookup $array has a full map of numbers and characters — upper and lower — to do an simple faux encryption with.

$array = array(
‘e’ => ‘ieio’
, ‘1’ => ‘one’
, ‘2’ => ‘two’
, ‘0’ => ‘zero’
);
var_dump ( $array );
$keys = array_keys ( $array );
var_dump ( $keys );

$string = ‘1e0’ ;
for ( $i = 0 ; $i < strlen ( $string ); $i ++) if ( in_array ( $string [ $i ], $keys , 'strict' )) echo 'dude ' ;
else echo ‘sweet ‘ ;
>
?>

Outputs:
array (size=4)
‘e’ => string ‘ieio’ (length=4)
1 => string ‘one’ (length=3)
2 => string ‘two’ (length=3)
0 => string ‘zero’ (length=4)

array (size=4)
0 => string ‘e’ (length=1)
1 => int 1
2 => int 2
3 => int 0

—-
expected to see:
dude dude dude

Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.

Invalid:
echo array_shift( array_keys( array(‘a’ => ‘apple’) ) );

Valid:
$keys = array_keys( array(‘a’ => ‘apple’) );
echo array_shift( $keys );

But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:

echo array_shift( ( array_keys( array(‘a’ => ‘apple’) ) ) );

However I would expect in time the PHP team will modify the rules of parentheses.

If an array is empty (but defined), or the $search_value is not found in the array, an empty array is returned (not false, null, or -1). This may seem intuitive, especially given the documentation says an array is returned, but I needed to sanity test to be sure:

$emptyArray = array();
var_dump ( array_keys ( $emptyArray , 99 )); // array (size=0) \ empty

$filledArray = array( 11 , 22 , 33 , 42 );
var_dump ( array_keys ( $filledArray , 99 )); // array (size=0) \ empty

# array_keys() also return the key if it’s boolean but the boolean will return as 1 or 0. It will return empty if get NULL value as key. Consider the following array:

$a = array(
«first_index» => «This is the first element» ,
true => 3 ,
false => 2 ,
4.5 => ‘Something’ ,
«08» => 5 ,
«8» => 6 ,
NULL => ‘Null key’
);

Array
(
[ 0 ] => first_index
[ 1 ] => 1
[ 2 ] => 0
[ 3 ] => 4
[ 4 ] => 08
[ 5 ] => 8
[ 6 ] =>
)

Keys from multi dimensional array to simple array

Want to traverse an multi dimensional array and get the keys back in a single dimensional array? This will do the trick:

foreach( $array as $key => $val ) $flattenedKeysArray [] = $key ;

if( is_array ( $val ))
array_walk_keys ( $val , $key , $flattenedKeysArray );
>

might be worth noting in the docs that not all associative (string) keys are a like, output of the follow bit of code demonstrates — might be a handy introduction to automatic typecasting in php for some people (and save a few headaches):

$r = array( «0» => «0» , «1» => «1» , «» => «2» , » » => «3» );
echo ‘how php sees this array: array(«0″=>»0″,»1″=>»1″,»» =>»2″,» «=>»3»)’ , «\n————\n» ;
var_dump ( $r ); print_r ( $r ); var_export ( $r );
echo «\n————\n» , ‘var_dump(«0″,»1″,»»,» «) = ‘ , «\n————\n» ;
var_dump ( «0» , «1» , «» , » » );
?>

OUTPUTS:

I wrote a function to get keys of arrays recursivelly.

function recursive_keys ( $input , $search_value = null )

$output = ( $search_value !== null ? array_keys ( $input , $search_value ) : array_keys ( $input )) ;
foreach( $input as $sub ) <
if( is_array ( $sub )) <
$output = ( $search_value !== null ? array_merge ( $output , recursive_keys ( $sub , $search_value )) : array_merge ( $output , recursive_keys ( $sub ))) ;
>
>
return $output ;
>
?>

I hope it will be usefull

Here’s a function I needed to collapse an array, in my case from a database query. It takes an array that contains key-value pairs and returns an array where they are actually the key and value.

function array_collapse ( $arr , $x , $y ) $carr = array();
while ( $el = current ( $arr )) $carr [ $el [ $x ] ] = $el [ $y ];
next ( $arr );
>
return $carr ;
>

?>

Example usage (pseudo-database code):

$query = db_query ( ‘SELECT name, value FROM properties’ );

$result = db_returnAll ( $query );

/* This will return an array like so:

[
[‘name’ -> ‘color’, ‘value’ -> ‘blue’],
[‘name’ -> ‘style’, ‘value’ -> ‘wide-format’],
[‘name’ -> ‘weight’, ‘value’ -> 3.6],
[‘name’ -> ‘name’, ‘value’ -> ‘Waerdthing’]]

$propArr = array_collapse ( $result , ‘name’ , ‘value’ );

/* Now this array looks like:

[
[‘color’ -> ‘blue’],
[‘style’ -> ‘wide-format’],
[‘weight’ -> 3.6],
[‘name’ -> ‘Waerdthing’],

Источник

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