我有一个我希望转换为多维的数组。
这是数组
Array
(
[0] => Array
(
[packageid] => FGF1460676803
[uniqueid] => uid1460676987
[hotelname] => Jet Park Airport
[Country] => New Zealand
)
[1] => Array
(
[packageid] => FGF1460678556
[uniqueid] => uid1460678681
[hotelname] => Mercure Windsor
[Country] => New Zealand
)
[2] => Array
(
[packageid] => FGF1460678556
[uniqueid] => uid1460678787
[hotelname] => Jet Park Airport
[Country] => New Zealand
)
)
我试过这段代码,但它没有显示我想要的。 这个数组从mysql的两个表中获取第一个是携带packageid,第二个是携带uniqueid,hotelname,country所以我联合它但是我想联合下面的数组但是我被困在如何使用mysql或者获取数组之后。
这是mysql查询
SELECT
c.packageid,
`uniqueid`,
`hotelname`,
`Country`
FROM
custinfo c,
hotelcarttemp h
WHERE
c.packageid = h.packageid
PHP代码
foreach ($json_decode_array1 as $row)
{
$newArray[$row['packageid']][] = $row;
}
echo '<pre>'; print_r($newArray); echo '</pre>';
想要OutPut
Array
(
[0] => Array
(
[packageid] => FGF1460676803
[hoteldata] => Array
(
[0] => Array
(
[uniqueid] => uid1460676987
[hotelname] => Jet Park Airport
[Country] => New Zealand
)
)
)
[1] => Array
(
[packageid] => FGF1460678556
[hoteldata] => Array
(
[0] => Array
(
[uniqueid] => uid1460678681
[hotelname] => Mercure Windsor
[Country] => New Zealand
)
[1] => Array
(
[uniqueid] => uid1460678787
[hotelname] => Jet Park Airport
[Country] => New Zealand
)
)
)
)
答案 0 :(得分:1)
试试这个:
$newArray = array();
foreach ($json_decode_array1 as $row)
{
$pid = $row['packageid'];
if (!isset($newArray[$pid])) {
$newArray[$pid] = array(
'packageid' => $pid,
'hoteldata' => array(),
);
}
// if you don't want `packageid`
// to present in a arrays of `hoteldata`
// you can `unset` this key:
unset($row['packageid']);
$newArray[$pid]['hoteldata'][] = $row;
}
// use array_values to turn array keys to numeric:
$newArray = array_values($newArray);
答案 1 :(得分:0)
试试这个
$newArr = array();
foreach($json_decode_array1 as $row) {
$temp = array();
$temp['packageid'] = $row['packageid'];
$temp['hoteldata'] = array(
'uniqueid' => $row['uniqueid'],
'hotelname' => $row['hotelname'],
'Country' => $row['Country'],
);
$newArr[] = $temp;
}
echo '<pre>';print_r($newArr);
答案 2 :(得分:0)
使用array_walk
,array_shift
和array_values
函数的解决方案:
$result = [];
array_walk($arr, function($v) use(&$result) { // $arr is your initial array
$packageid = array_shift($v);
if (!isset($result[$packageid])) {
$result[$packageid] = ["packageid" => $packageid, "hoteldata" => [$v]];
} else {
$result[$packageid]["hoteldata"][] = $v;
}
});
print_r(array_values($result));
输出:
Array
(
[0] => Array
(
[packageid] => FGF1460676803
[hoteldata] => Array
(
[0] => Array
(
[uniqueid] => uid1460676987
[hotelname] => Jet Park Airport
[Country] => New Zealand
)
)
)
[1] => Array
(
[packageid] => FGF1460678556
[hoteldata] => Array
(
[0] => Array
(
[uniqueid] => uid1460678681
[hotelname] => Mercure Windsor
[Country] => New Zealand
)
[1] => Array
(
[uniqueid] => uid1460678787
[hotelname] => Jet Park Airport
[Country] => New Zealand
)
)
)
)