我真的需要有关数组的帮助。我有这样的案例
[
{"animal":"lion", "car":"honda"},
{"animal":"rabbit","car":"BMW"},
{"animal":"rat", "car":"Toyota"},
{"animal":"mouse", "car":"Suzuki"},
{"animal":"horse", "car":"mercedes"},
{"animal":"dog", "car":"Jaguar"},
{"animal":"cat", "car":"Audi"}
]
如何在PHP代码中拆分成为这样的2类
$animal = [ "lion","rabbit","rat","mouse","horse","dog","cat"];
和
$car = ["honda","BMW","Toyota","Suzuki","mercedes","Jaguar","Audi"];
我真的需要解决这个问题。请帮帮我
答案 0 :(得分:4)
Json_decode字符串并使用array_column获取每个变量中的列。
$json = '[
{"animal":"lion", "car":"honda"},
{"animal":"rabbit","car":"BMW"},
{"animal":"rat", "car":"Toyota"},
{"animal":"mouse", "car":"Suzuki"},
{"animal":"horse", "car":"mercedes"},
{"animal":"dog", "car":"Jaguar"},
{"animal":"cat", "car":"Audi"}
]';
$arr = json_decode($json,1);
$animals = array_column($arr, "animal");
$cars = array_column($arr, "car");
var_dump($cars, $animals);
答案 1 :(得分:2)
真的很容易。解码json,创建两个空白数组,循环遍历,并添加到每个数组:
<?php
$x = '[
{"animal":"lion", "car":"honda"},
{"animal":"rabbit","car":"BMW"},
{"animal":"rat", "car":"Toyota"},
{"animal":"mouse", "car":"Suzuki"},
{"animal":"horse", "car":"mercedes"},
{"animal":"dog", "car":"Jaguar"},
{"animal":"cat", "car":"Audi"}
]';
$y = json_decode($x, true);
$animals = [];
$cars = [];
foreach ($y as $z) {
$animals[] = $z['animal'];
$cars[] = $z['car'];
}
var_dump($animals);
var_dump($cars);
答案 2 :(得分:1)
试试:
$arr=json_decode('[
{"animal":"lion", "car":"honda"},
{"animal":"rabbit","car":"BMW"},
{"animal":"rat", "car":"Toyota"},
{"animal":"mouse", "car":"Suzuki"},
{"animal":"horse", "car":"mercedes"},
{"animal":"dog", "car":"Jaguar"},
{"animal":"cat", "car":"Audi"}
]');
var_dump($arr);echo'<br>';echo'<br>';
$animal=array();
$car=array();
foreach ($arr as $row){
$animal[]=$row->animal;
$car[]=$row->car;
}
var_dump($car);
var_dump($animal);