简体   繁体   中英

PHP Dynamic Nested Associative Array

I have an associative array which is generated dynamically with the values from database. When I print the whole array, it gives something like this when we put print_r($array).

  Array ( [95a5c80811239526fb75cbf31740cc35] => Array ( [product_id] => 2324) )

When I echo like this,

echo $array['95a5c80811239526fb75cbf31740cc35']['product_id'];

it gives me product id. But the problem is, the code '95a5c80811239526fb75cbf31740cc35' changes dynamically everytime. I want to echo the product id irrespective of this code.

I tried

$array[]['product_id'];
$array['']['product_id'];

But not working. Can anyone help me? Please ask me if you have any doubts.

You can use reset() in this case:

$array = array(
    '95a5c80811239526fb75cbf31740cc35' => array( // dynamic
        'product_id' => 2324
    ),
);

$value = reset($array); // set pointer to first element
echo $value['product_id']; // 2324

Assuming that the code is always the first element in the array:

$array[0]['product_id'];

If you collectively want all of the product ID's:

foreach($array as $product){
    $productIds[] = $product['product_id'];
}

// $productIds is now what $array was, but without the codes, so the product_id's are the first elements.

You can use for each for this so that you can get the value of product Id

 $array = Array ( [95a5c80811239526fb75cbf31740cc35] => Array ( [product_id] => 2324) )

foreach($array as $product){
echo $product['product_id'];
}

This would get your desired o/p

Depending on your situation, there are few possible solutions:

$array = array_shift(array_values(
  Array(
    '95a5c80811239526fb75cbf31740cc35' =>
       Array(
          'product_id' => 2324
       )
    )));

echo $array['product_id']; // 2324

Another solution, probably more efficient:

echo array_shift(array_slice($array, 0, 1)); // 2324

For PHP 5.4+ you could go with:

echo array_values($array)[0]; // 2324

IF you are getting problem using Associative array then you can first convert it into numeric as follows

    $arr=array( 'first' => array( 'product_id' => 2324) );
    $arrr=array_values($arr);
     echo $arrr[0]['product_id'];

Output:

2324

Hope this helps and to know about array_values go here

$array[0]['product_id'];

应该做到的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM