splite value array ini php

时间:2018-05-14 12:39:15

标签: php arrays

我真的需要有关数组的帮助。我有这样的案例

[
   {"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"];

我真的需要解决这个问题。请帮帮我

3 个答案:

答案 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);

https://3v4l.org/NtL9e

答案 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);

https://3v4l.org/Fb7Bq

答案 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);