使用PHP从数组中获取数据

How from this array:

Array
(
    [2017-04-10] => 0
    [2017-04-11] => 95
    [2017-04-12] => 101.67
)

I can get something like this:

$dates = "2017-04-10, 2017-04-11, 2017-04-12";
$price = "0, 95, 101.67";

Thanks.

Here we are using array_keys , array_values and implode.

1. array_keys return keys of an array

2. array_values return values of an array

3. implode joins array with a glue

Try this code snippet here

<?php

ini_set('display_errors', 1);

$array=Array
(
    "2017-04-10" => 0,
    "2017-04-11" => 95,
    "2017-04-12" => 101.67
);
echo $dates=implode(", ",  array_keys($array));
echo PHP_EOL;
echo $price=implode(", ",  array_values($array));

Just use array_keys and array_values and implode.

  1. array_keys() will get the all the key from array as new array.

  2. array_values() will get the all values form array as new array.

  3. implode() will convert your array into string with separated by comma delimiter.

implode(', ', array_keys($data));
implode(', ', array_values($data));
$data = ['2017-04-10' => 0, '2017-04-11' => 95, '2017-04-12' => 101.67];
$dates = implode(',', array_keys($data));
$prices = implode(',', array_values($data));

The previous answers are definetly the most concise. But if you needed to do any manipulation on the data (like escape delimiter characters, or encapsulate in quotes, or change the date format or add a currency symbol), this might be the most flexible...

foreach($arr as $date => $val) {
  $datestr .= $date.',';
  $valstr .= $val.',';
}

if you need to trim off the trailing comas you could do

$datestr = rtrim($datestr,',');
$valstr = rtrim($valstr,',');

Several of the answers on this page unnecessarily call array_values(). I think the posters were just rushing their answers. You can omit this extra function call and achieve the same result:

Method:

$array=[
    "2017-04-10" => 0,
    "2017-04-11" => 95,
    "2017-04-12" => 101.67
    ];
$dates=implode(', ',array_keys($array));    // 2017-04-10, 2017-04-11, 2017-04-12
$price=implode(', ',$array);                // 0, 95, 101.67

This is the leanest, most efficient answer to your question.