如何将任何字符串、数字或对象转换为数组


How do I convert any string, number, or object into an array?

例如,我用simplexml_load_file()加载了一些东西,但我想要输出是一个数组而不是一个对象。

或者,假设我有一个动态值,有时是字符串,有时是数组,其他时候是对象(我不知道输入是什么,但我想要输出始终是一个数组)。

确保我所拥有的任何值都作为数组返回给我的最佳方法是什么?

这是我见过的最好的方法。

/**
 * Convert any string, number, object, etc, to an array.
 *
 * @param (mixed) $input
 *  The value to be converted into an array.
 *
 * @return (array)
 *   The original input as an array. If the input value is an empty string or empty
 *   array, the return value will be an empty array.
 */
function arrayify($input) {
  // Zero means empty, so make sure not to include actual zeros as being "empty"
  // since the desired output might be array(0)
  if (empty($input) && $input !== 0) {
    // Empty in, empty (array) out.
    return array();
  }
  return unserialize(serialize(json_decode(json_encode((array) $input), 1)));
}

我希望他们能让它(或其衍生物)成为PHP的核心函数,但由于我没有我想我很可能会在这里分享。任何反馈或改进是受欢迎的(假设这不违反规则)

或者您可以使用json_decode和foreach循环

$result = json_decode(XXX);
foreach ($result as $data) {
  echo $data->arr1;
  echo $data->arr1->arr2;
  ...
  ...
}