正确格式化PHP输出

3

我做了一些研究,但我找不到我要找的东西。虽然我不是PHP专家,但我认为我正在尝试做一些相当简单的事情。

在Unity3D中,我想从执行post请求后获取的PHP输出中接收几个值。

输出来自arangoDB,看起来像这样:

array(1) {
  [0]=>
  object(ArangoDBClient\Document)#9 (9) {
    ["_id":protected]=>
    string(16) "Producten/140368"
    ["_key":protected]=>
    string(6) "140368"
    ["_rev":protected]=>
    string(11) "_WMOJhJe--_"
    ["_values":protected]=>
    array(3) {
      ["Naam Product"]=>
      string(9) "Naam-Foo2"
      ["Categorie Product"]=>
      string(14) "Categorie-Foo2"
      ["Discipline Product"]=>
      string(15) "Discipline-Foo2"
    }
    ["_changed":protected]=>
    bool(true)
    ["_isNew":protected]=>
    bool(false)
    ["_doValidate":protected]=>
    bool(false)
    ["_hiddenAttributes":protected]=>
    array(0) {
    }
    ["_ignoreHiddenAttributes":protected]=>
    bool(false)
  }
}

我只对这部分内容感兴趣:
["Naam Product"]=>
      string(9) "Naam-Foo2"
      ["Categorie Product"]=>
      string(14) "Categorie-Foo2"
      ["Discipline Product"]=>
      string(15) "Discipline-Foo2"

最理想的情况下,它应该像这样格式化:

Naam Product: Naam-Foo2;
Categorie Product: Categorie-Foo2;
Discipline Product: Discipline-Foo2;

如何过滤这些信息,以便在Unity中读取时获得干净的数据字符串?

对此有任何建议吗?先谢谢了!

2个回答

1
尝试使用 getAll 方法:
$interested_array = $filter[0]->getAll();
print_r($interested_array);

它给我这个错误:致命错误:在C:\xampp\htdocs\ArangoTest\index.php的第62行抛出了“未捕获的错误:无法将类型为ArangoDBClient \ Cursor的对象用作数组。堆栈跟踪:#0 {main}” 。我删除了[],现在输出已经干净了一些!它似乎是一个数组中的数组。你如何过滤它? - sirJ

1
据我所知,从服务器向客户端发送JSON数据更好。只需将Newtonsoft.Json库添加到您的Unity3D项目中即可。然后,您可以轻松地将接收到的json字符串反序列化为C#对象。以下是一个简单的示例:
string jsonString = "Your json string";

var deserializedObject = Newtonsoft.Json.JsonConvert.DeserializeObject<YOUR_POCO_OBJECT>(jsonString);

现在您可以使用deserializedObject字段。
这是一个简单的C#控制台应用程序示例。
namespace JsonDEMO
{
    public class Product
    {
        public string Name { get; set; }
        public string Category { get; set; }
        public string Discipline { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string jsonString = "{ 'Name': 'Naam-Foo2','Category': 'Categorie-Foo2','Discipline': 'Discipline-Foo2'}";

            var deserializedObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(jsonString);

            System.Console.WriteLine(deserializedObject.Name);
            System.Console.WriteLine(deserializedObject.Category);
            System.Console.WriteLine(deserializedObject.Discipline);
        }
    }
}

是的,我认为你是正确的。我已经阅读过相关资料,但在我发送 PHP 中的 JSON 字符串之前,我认为我需要将其清理一下,只留下我需要的部分?因为现在我只有一个简单的数组,我可以将其转换为 JSON,然后在 Unity 中接收它作为 JSON。至少这就是我现在正在尝试做的 :)我已经添加了 "echo json_encode($interested_array);",现在我有了干净的 JSON 输出,感谢您的帮助。 - sirJ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接