gpt4 book ai didi

php - MYSQL PHP 数组分组

转载 作者:行者123 更新时间:2023-11-29 06:28:38 26 4
gpt4 key购买 nike

我在概念上无法理解这个问题。对此还很陌生。基本上我从数据库中得到了这样的返回:

array (size=456)
0 =>
object(stdClass)[358]
public 'id' => string '2432' (length=4)
public 'symbol' => string '.AMLP' (length=14)
public 'last' => string '0.01' (length=4)
public 'volume' => string '3690' (length=4)
public 'the_date' => string '2019-09-13' (length=10)
public 'the_screener' => string '1' (length=1)
public 'notes' => string 'notes here' (length=149)
1 =>
object(stdClass)[726]
public 'id' => string '2417' (length=4)
public 'symbol' => string '.ARCC' (length=14)
public 'last' => string '2.25' (length=4)
public 'volume' => string '1633' (length=4)
public 'the_date' => string '2019-09-13' (length=10)
public 'the_screener' => string '1' (length=1)
public 'notes' => string 'notes' (length=60)
2 =>
object(stdClass)[726]
public 'id' => string '2447' (length=4)
public 'symbol' => string '.ARCC' (length=14)
public 'last' => string '2.25' (length=4)
public 'volume' => string '1633' (length=4)
public 'the_date' => string '2019-09-12' (length=10)
public 'the_screener' => string '1' (length=1)
public 'notes' => string 'notes here 3' (length=60)
3 =>

我试图用 PHP 做的是创建一个对象/数组,我可以使用它来显示这些项目,例如

AMLP 1 found on dates 2019-09-13
ARCC 2 found on dates 2019-09-13, 2019-09-12

最后我会将这些显示在表格中,但从概念上讲,这就是我想要做的。

我尝试在我的 foreach 中创建一个数组,用于在表中显示此信息,但我正在考虑它,最好只使用相同的查询数据并将其单独分解。

所以我想创建一个像这样的数组:

    Array
(
[1] => Array
(
[id] => 1
[symbol] => ARCC
[dates] => Array
(
[3] => Array
(
2019-09-13
2019-09-12
)

)

)

)

最佳答案

假设您的数组是$arrDates。如果您想访问对象属性之类的属性

$arrFinal = [];
foreach ($arrDates as $intKey => $obj){
$strSymbol = getSubSymbol($obj->symbol);
if(!isset($arrFinal[$strSymbol])) {
$arrFinal[$strSymbol] = [ 'id' => $obj->id, 'symbol' => $obj->symbol];
}

$arrFinal[$strSymbol]['dates'][] = $obj->the_date;
}

// Now loop throuh arrFinal and do print the statements you want.
foreach($arrFinal as $strSubSymbol => $arrData){
echo $strSubSymbol . ' '. count($arrData['dates']) . ' found on dates ' . implode(',', $arrData['dates']). PHP_EOL;
}

获取符号所需子部分的函数

function getSubSymbol($symbol_original){
$symbol = preg_split('/(?=\d)/', $symbol_original, 2); //get everything up until first number or the date in the string in this case.
$symbol_here = substr($symbol[0], 1);
return $symbol_here;
}

关于php - MYSQL PHP 数组分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57932724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com