PHP将Object Array的字段复制到一个简单的Array中

时间:2015-11-18 12:35:49

标签: javascript php ajax bash

我有一个PHP Object Array有几个字段,我需要提取所有相等的字段并将它们存储到individual arrays中,因为我需要将它们传递给bash script我希望有单独的数组,因为bash不是面向对象的吗?

以下是我要做的事情:

<?php 
$data = json_decode($_POST['data']);

$text_array = "'" . implode ("\n", $data->text) . "'";
$time_text = "'" . implode ("\n", $data->time_text) . "'";
$gender = "'" . implode ("\n", $data->gender) . "'";
$pitch = "'" . implode ("\n", $data->pitch) . "'";

$response = shell_exec("./test_bash.sh $pitch $gender $timetext $text_array 2>&1");

echo "$response";

?>

数据从javascript传递到PHPajax。原始Object Array具有以下结构:

text
time_text
gender
pitch

我在Object Array中创建了Javascript,如:

function dataClass(text, time_txt, gender, pitch, mood) {
        this.text = text;
        this.time_text = time_txt;
        this.gender = gender;
        this.pitch = pitch;
        this.mood = mood;
}
for(var i = 0; i < length - 1; i++){
    data.push(new dataToSynth(subtitles_trans[i].text, subtitles_trans[i].end - subtitles_trans[i].start, genere, pitch));
}

如何在PHP中将对象数组字段复制到单个数组?

2 个答案:

答案 0 :(得分:1)

您不需要使用json_decode。在你的情况下“$ _POST ['data']”是一个数组,而不是一个对象。试试这段代码:

$data = $_POST['data'];

$text_array = "'" . implode ("\n", $data['text']) . "'";
$time_text = "'" . implode ("\n", $data['time_text']) . "'";
$gender = "'" . implode ("\n", $data['gender']) . "'";
$pitch = "'" . implode ("\n", $data['pitch']) . "'";

答案 1 :(得分:1)

只要将字符串转换为int,就可以将对象值转换为数组。

it2.second.insert( make_pair(2013,"russian translaiton")  );

所以它应该是这样的:

<?php
class a{
    public $a="a";
    public $b="b";
    public $c="c";
}

$a= new a();

$b= (array)$a;

var_dump($a);
/*object(a)#1 (3) {
    ["a"]=>
       string(1) "a"
    ["b"]=>
       string(1) "b"
    ["c"]=>
       string(1) "c"
}*/
var_dump($b);
/*array(3) {
    ["a"]=>
       string(1) "a"
    ["b"]=>
       string(1) "b"
    ["c"]=>
       string(1) "c"
}*/