我继续为你准备了一堂课。基本上我遍历两个数组并创建一个仅包含两个数组中的文本数据的新数组。创建新数组后(检查具有相同文本的现有数组数据 - 没有重复),我为每个原始数组设置布尔变量,然后循环遍历唯一文本字符串数组并检查每个数组中的文本字符串。如果我在原始数组之一中找到文本,我会更改相应原始数组的布尔值。我测试两个布尔变量的值并相应地设置新的 $socialArr 值。希望这是有道理的。代码经过测试并且可以工作。
<?php
class socialArray {
public function init($twitter,$facebook){
$this->combinedText = $this->combinedTextArr($twitter,$facebook);
$this->socialArr = $this->makeSocialArr($twitter,$facebook);
return $this->socialArr;
}
public function combinedTextArr($twitter,$facebook){
$combinedText = array();
foreach($twitter as $key => $value){
if( !in_array($value["text"],$combinedText ) ){
$combinedText[] = $value["text"];
}
}
foreach($facebook as $key => $value){
if( !in_array($value["text"],$combinedText ) ){
$combinedText[] = $value["text"];
}
}
return $combinedText;
}
public function makeSocialArr($twitter,$facebook){
$socialArr = array();
foreach($this->combinedText as $value){
$twitterTest = false;
$facebookTest = false;
foreach($twitter as $var){
if( $var["text"] == $value) {
$twitterTest = true;
}
}
foreach($facebook as $var){
if( $var["text"] == $value ) {
$facebookTest = true;
}
}
if( $twitterTest === true && $facebookTest === false ) {
$socialArr[] = array(
'text' => $value,
'type' => 'twitter'
);
} else if ( $twitterTest === false && $facebookTest === true ) {
$socialArr[] = array(
'text' => $value,
'type' => 'facebook'
);
} else if ( $twitterTest === true && $facebookTest === true ) {
$socialArr[] = array(
'text' => $value,
'type' => 'both'
);
}
}
return $socialArr;
}
}
$facebook = array();
$facebook[] = array(
"text" => "A post on facebook with text and stuff",
"type" => "facebook"
);
$facebook[] = array(
"text" => "This occurs in both arrays",
"type" => "facebook"
);
$twitter = array();
$twitter[] = array(
"text" => "A tweet of the utmost importance",
"type" => "twitter"
);
$twitter[] = array(
"text" => "This occurs in both arrays",
"type" => "twitter"
);
$socArrMaker = new socialArray();
$socialArr = $socArrMaker->init($twitter,$facebook);
echo "<html><head><style type=\"text/css\">body{ font-family: sans-serif; }</style></head><body><pre>\r\n";
print_r($socialArr);
echo "</pre></body></html>\r\n";
产生...
Array
(
[0] => Array
(
[text] => A tweet of the utmost importance
[type] => twitter
)
[1] => Array
(
[text] => This occurs in both arrays
[type] => both
)
[2] => Array
(
[text] => A post on facebook with text and stuff
[type] => facebook
)
)