我有这样的数组
[
{
"id": "2",
"first_name": "hassan",
"last_name": "hassani",
"created": "0000-00-00 00:00:01",
},
{
"id": "3",
"first_name": "mohamad",
"last_name": "mohamadi",
"created": "0000-00-00 00:00:00",
}
]
我想将此数组转换为这样的数组
[
{
"first_name" : "hassan",
"last_name" : "hassani",
},
{
"first_name" : "mohamad",
"last_name" : "mohamadi",
}
]
我该怎么做?
谢谢您的回答
答案 0 :(得分:2)
这将解决您的问题。您可以使用array_map()函数迭代每个值。
Array
(
[0] => Array
(
[first_name] => hassan
[last_name] => hassani
)
[1] => Array
(
[first_name] => mohamad
[last_name] => mohamadi
)
)
输出:
{{1}}
答案 1 :(得分:1)
您可以使用id
和created
键,使用array_map和unset从阵列中删除项目:
$result = array_map(function($x) {
unset($x['id'], $x['created']);
return $x;
}, $arrays);
这将导致:
Array
(
[0] => Array
(
[first_name] => hassan
[last_name] => hassani
)
[1] => Array
(
[first_name] => mohamad
[last_name] => mohamadi
)
)
答案 2 :(得分:0)
您已经尝试过什么?我了解,当您(相对)不熟悉php和/或编程时,这些东西可能很难理解-我假设您是这样,否则应该真正删除此问题。
关于数组的一些good information,以及如何遍历它们。一探究竟! W3C通常具有一些良好且易于理解的信息...
我将通过遍历数组并删除所有您不想保留的条目来解决这个问题-即不在您要保留的键数组中。或者,您可以通过指定需要删除的密钥来做到这一点。例如:
<?php
$array = [
[
"id" => "2",
"first_name" => "hassan",
"last_name" => "hassani",
"created": "0000-00-00 00:00:01",
],
[
"id": "3",
"first_name" => "mohamad",
"last_name" => "mohamadi",
"created" => "0000-00-00 00:00:00",
]
]
$keepers = ["first_name", "last_name"]; // Make an array of keys we want to keep.
foreach ($array as $arr) { // Loop over the outer array
foreach ($arr as $key => $value){ // Loop over the inner array that actually holds the key=> value pairs.
if (!in_array($key, $keepers)){ // Determine whether we want to keep this key.
unset($arr[$key]) // This key is not in the $keepers-array, we'll go ahead and delete (i.e. unset) it.
}
}
}
答案 3 :(得分:-1)
有很多方法可以做到这一点,但这是我首先想到的。重新做阵列。我将在下面提供的方法将为您提供一个示例,说明如何在不覆盖当前数组的情况下执行此操作,以防日后需要时使用它。这种方法也很灵活。
<?php
$array = Array(); //you won't need this, let's just assume we're using the array from your original post
$newArray = Array(); //create a new array, this will have less values than the original
foreach ($array as $k=>$v){
if ($k == "first_name" or $k == "last_name"){ //only add to array if the key is "first_name" or "last_name"
$newArray[$k] = $v; //adds it to $newArray
}
}
print_r($newArray);
?>
祝您好运!另外请注意,我没有测试此代码。