## 能否设计一个这样的函数 去操作数组？

mirai_ 发布于 2013/12/16 14:02

```\$arr = array(
1 => 1,
2 => array(
3 => 3,
4 => 4,
5 => array(
6 => 6,
7 => 7,
8 => array(
9  => 9,
10 => 10
),
)
)
);
/*
function arrayValue(\$arr,\$path,\$value = null){}
*/
arrayValue(\$arr,'2,4',44);//等价于 \$arr[2][4] = 44
arrayValue(\$arr,'2,5,8,10',100);//等价于 \$arr[2][5][8][10] = 100
arrayValue(\$arr,'2,4');//等价于 获取 \$arr[2][4] 的值
//这样获取数组的值就更加方便！```

0
```<?php
function arrayValue(&\$arr,\$path,\$value = null){
\$p=explode(",",\$path);
\$temparr = \$arr;
\$arr2 = &\$temparr;
foreach (\$p as \$k => \$v) {
is_array(\$arr2)||\$arr2=array();
\$arr2 = &\$arr2[\$v];
}
if(isset(\$value)){
\$arr2 = \$value;
\$arr = \$temparr;
}
return \$arr2;
}
\$array = array();
arrayValue(\$array,"1,10,9",111);
arrayValue(\$array,"2,10",222);
arrayValue(\$array,"2,10,9",333);
print_r(\$array);
print_r(arrayValue(\$array,"2,10"));
print_r(arrayValue(\$array,"2,10,9,99"));
print_r(\$array);```

@上帝未满18岁 做了些容错的修改

0

0

#### 引用来自“布尔道长”的答案

0

```var arrayValue = function (array, indexStr) {
var indexs = indexStr.split(",");
var re = array;
for (var i in indexs) {
re = re[indexs[i]];
}
return re;
}

alert(arrayValue([[1, 2, 3, 4], [1, 2, 3, 4], 3, 4], "1,2"));```

0

#### 引用来自“欢乐的财神”的答案

```var arrayValue = function (array, indexStr) {
var indexs = indexStr.split(",");
var re = array;
for (var i in indexs) {
re = re[indexs[i]];
}
return re;
}

alert(arrayValue([[1, 2, 3, 4], [1, 2, 3, 4], 3, 4], "1,2"));```

0

#### 引用来自“鑫酱”的答案

```<?php

function arrayValue(&\$arr,\$path,\$value = null){
\$p=explode(",",\$path);
\$arr2 = &\$arr;
foreach (\$p as \$k => \$v) {
\$arr2 = &\$arr2[\$v];
}
if (\$value===null) {
return \$arr2;
}else{
\$arr2 = \$value;
}
}

\$array = array();
arrayValue(\$array,"2,10",1111);
print_r(\$array);
print_r(arrayValue(\$array,"2,10"));```

0
```<?php

\$arr = array(
1 => 1,
2 => array(
3 => 3,
4 => 4,
5 => array(
6 => 6,
7 => 7,
8 => array(
9  => 9,
10 => 10
),
)
)
);

function arrayValue(\$arr,\$path,\$value=null)
{
\$array = array();
\$p = explode(',',\$path);

\$count = count(\$p);

for(\$i=0;\$i<\$count;\$i++)
{
if(\$i==0)
{
\$array = \$arr[\$p[\$i]];
}
else
{
\$array = \$array[\$p[\$i]];
}

}

\$array = !empty(\$value) ? \$value : \$array;

return \$array;
}

echo arrayValue(\$arr,'2,4');//等价于 获取 \$arr[2][4] 的值

var_dump(\$arr);

\$arr[2][4] = arrayValue(\$arr,'2,4',44);//等价于 \$arr[2][4] = 44

var_dump(\$arr);```

0