42973

Accessing nested associative array using array_keys (PHP)

Question:

I'm trying to access a nested associative array:

$data = array('1'=>'value1','2'=>'value2','3'=>array('one','two'))

The value of the key '3' is an array.

Since I need to cycle my values, I extracted the keys of given array:

$keys = array_keys($data);

and used to get the associated value with:

foreach(range(1, 10) as $val): echo "key: ".$keys[$val]; echo "value: ".$data[$keys[$val]]; endforeach;

Now I would like to access the values related to '3'. Using $data[$keys[$val]] won't work cause I get back an array, not a value.

My question is: how can I access, for example to the value 'one' using a syntax close to $data[$keys[$val]] ?

Answer1:

You should add a condition to check if the value is a string or an array. If it's a string - simply echo it, otherwise - access the first value in that array (key = 0, will print 'one') or use another foreach loop to access all of those array's values.

foreach(range(1, 10) as $val): echo "key: ".$keys[$val]; echo "value: "; if(is_array($data[$keys[$val]])){ //Is it an array? //echo 'one' echo $data[$keys[$val]][0]; //or all the values with a loop foreach($data[$keys[$val]] as $val2){ echo $val2; echo ","; } } else { //it's not an array, we can simply echo it. echo $data[$keys[$val]]; } endforeach;

Recommend

  • use preg_replace to replace whole words using associative array
  • php, how to jumble / randomize order of associative array while keeping key/value pairs
  • How to check for existence of parameter in url?
  • Wordpress: Limit Tag Links in Post Content
  • Push on every field of an array PHP
  • Adding properties to UIControls without subclassing
  • When does an action not run on the driver in Apache Spark?
  • can a php $_SESSION variable have numeric id thus : $_SESSION['1234’]
  • Download data first then show it on TableViewcontroller
  • C++ DLL Wrapper in vb.net Passing byte array of a byte array?
  • pandas parse csv with left and right quote chars
  • how to remove a div with same ids but display='block' and display='none' in JAVa
  • In Akka, is ActorContext thread safe?
  • Creating My Symmetric Key in C#
  • Draw half infinite lines?
  • Extract All Possible Paths from Expression-Tree and evaluate them to hold TRUE
  • XSLT foreach repeating nodes to flat
  • List images(01.png) and descriptions(01.txt) from directory
  • Array with custom indexes in Ionic2
  • Excel's Macro-Recorder usage
  • D3 nodes and links from JSON with nested arrays of children
  • ilmerge with a PFX file
  • Why value captured by reference in lambda is broken? [duplicate]
  • Check if a string to interpolate provides expected placeholders
  • How to handle AllServersUnavailable Exception
  • Javascript + PHP Encryption with pidCrypt
  • Convert array of 8 bytes to signed long in C++
  • VBA Convert delimiter text file to Excel
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Confusion with PayPal's monthly billing cycle
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • Benchmarking RAM performance - UWP and C#
  • Angular 2 constructor injection vs direct access
  • Understanding cpu registers
  • Why joiner is not used after Sequence generator or Update statergy
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Recursive/Hierarchical Query Using Postgres
  • Running Map reduces the dimensions of the matrices
  • Reading document lines to the user (python)
  • UserPrincipal.Current returns apppool on IIS