Hi i have a PHP array that looks like this When var_dumped
array (size=3)
0 =>
array (size=8)
'Product_code' => string 'CAB55FR' (length=7)
'Elapsed' => string '0' (length=1)
'Count' => string '42' (length=2)
'Scrap' => string '0' (length=1)
'ScrapPercentage' => string '0.00' (length=4)
'Perhour' => null
'Target' => float 40
'Eff' => string '105%' (length=4)
1 =>
array (size=8)
'Product_code' => string 'MSTACK60' (length=8)
'Elapsed' => string '0.05' (length=4)
'Count' => string '0' (length=1)
'Scrap' => string '0' (length=1)
'ScrapPercentage' => null
'Perhour' => string '0.00' (length=4)
'Target' => string 'No Target set' (length=13)
'Eff' => string 'No Target set' (length=13)
However what i want the array to look like is this
array (size=3)
0 =>
object(stdClass)[8]
public 'Product_code' => string 'CAB55FR' (length=7)
public 'Elapsed' => string '0' (length=1)
public 'Count' => string '42' (length=2)
public 'Scrap' => string '0' (length=1)
public 'ScrapPercentage' => string '0.00' (length=4)
public 'Perhour' => null
1 =>
object(stdClass)[9]
public 'Product_code' => string 'MSTACK60' (length=8)
public 'Elapsed' => string '0.05' (length=4)
public 'Count' => string '0' (length=1)
public 'Scrap' => string '0' (length=1)
public 'ScrapPercentage' => null
public 'Perhour' => string '0.00' (length=4)
To create the first array i am using this snippet of code
$todayarray[] = Array(
'Product_code' => $v->Product_code,
'Elapsed' => $v->Elapsed,
'Count' => $v->Count,
'Scrap' => $v->Scrap,
'ScrapPercentage' => $v->ScrapPercentage,
'Perhour' => $v->Perhour,
'Target' => $value,
'Eff' => $eff
);
this is run in a foreach, What would be the best way to get the array this is generating to look like the second example?
foreach($top_array as $item) {
$object = news stdClass;
$object->... = $item[...];
$object->... = $item[...];
...
object_array[] = $object;
}
Something like this would work:
$todayarr = new stdClass;
$properties = array('prop1', 'prop2');
foreach ($properties as $p)
$todayarr->$p = 'some value of property ' . $p;
var_dump($todayarr);
The simplest way would be to just cast the array to an object.
$todayarray[] = (object) Array( ... );
See a working demo.
Read more about type casting on the PHP manual