如何使用数组(PHP)所有偶数索引的元素键,将所有的奇数元素 [英] How to use all the even number indexed elements of array as key to all the odd numbered elements (PHP)
问题描述
我有一个数组,看起来像这样:
阵列(10){
[0] =>
串(10)2012年11月3日
[1] =>
串(1)为1
[2] =>
串(10)2012年11月4日
[3] =>
串(1)3
[4] =>
串(10)2012年11月5日
[5] =>
串(1)2
[6] =>
串(10)2012年11月6日
[7] =>
串(1)7
[8] =>
串(10)2012-11-07
[9] =>
串(1)4
}
我想从这个新的多维数组这将有5个元素,其中每个元素是这样的:$日期=> $号
阵列(5){
[0] =>阵列(2012年11月3日=→1)
[1] =>阵列(2012年11月4日=→3)
[2] =>阵列(2012年11月5日=→2)
[3] =>阵列(2012年11月6日=大于7)
[4] =>阵列(2012-11-07 =→4)
}
我想使用的日期作为关键TE后他们都值。 (我最终想一个折线图,其中x轴有日期上绘制这些值和y的值为)
什么样的的(的foreach?)循环可我写的做到这一点?
我从code以下行获得此阵
$数据=$起始日期\\ n $的值\\ N的;
的file_put_contents($ ID'的.csv',$数据,FILE_APPEND);
$数据=的file_get_contents($ ID的.csv');
$ data_array中=爆炸(\\ n,修剪($的数据,\\ n));
后续代码var_dump($ data_array中);出口;
我假设你的数组包含偶数元素,符合市场预期。
您可以使用下面的代码片段:
< PHP$ newArray =阵列();
为($ I = 0; $ I<计数($ data_array中); $ I + = 2){
$ newArray [$ data_array中[$ i]] = $ data_array中[$ I + 1];
}?>
^以上code说,我们开始在 $ data_array中
的指数 0
,这是一个日期。它使从偶数元素 newArray
的关键,并附加一个奇数元素此键的值。数组将是这样的:
阵列(
2012年11月3日'=> 1,
2012年11月4日'=> 3,
2012年11月5日'=> 2,
...
)
I have an array which looks like this:
array(10) {
[0]=>
string(10) "2012-11-03"
[1]=>
string(1) "1"
[2]=>
string(10) "2012-11-04"
[3]=>
string(1) "3"
[4]=>
string(10) "2012-11-05"
[5]=>
string(1) "2"
[6]=>
string(10) "2012-11-06"
[7]=>
string(1) "7"
[8]=>
string(10) "2012-11-07"
[9]=>
string(1) "4"
}
I would like to get a new multidimensional array from this which would have 5 elements, where each element would look like this: $date => $number.
array(5) {
[0]=> array(2012-11-03 => 1)
[1]=> array(2012-11-04 => 3)
[2]=> array(2012-11-05 => 2)
[3]=> array(2012-11-06 => 7)
[4]=> array(2012-11-07 => 4)
}
I would like to use the dates as keys to te values that come after them. (I would eventually like to plot these values on a line chart, where x axis has the date and y has the value)
What kind of a (foreach?) loop can I write to do this?
I am getting this array from the following lines of code:
$data = "$start_date\n$value\n";
file_put_contents($id . '.csv', $data, FILE_APPEND);
$data = file_get_contents($id . '.csv');
$data_array = explode("\n", trim($data, "\n"));
var_dump($data_array); exit;
I assume that your array contains an even number of elements, as expected.
You can use the following snippet:
<?php
$newArray = array();
for ($i = 0; $i < count($data_array); $i += 2) {
$newArray[$data_array[$i]] = $data_array[$i + 1];
}
?>
^ Above code says that we start at index 0
of $data_array
, which is a date. It makes a key in newArray
from the even element, and attaches the value of the next odd element to this key. The array will look like this:
Array(
'2012-11-03' => "1",
'2012-11-04' => "3",
'2012-11-05' => "2",
...
)
这篇关于如何使用数组(PHP)所有偶数索引的元素键,将所有的奇数元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!