Doctrine hydrated array result - php

I want to get Doctrine to return a hydrated array with the values being the id for the key, then all values inside an array of results (i.e. if there are multiple items with same ID, then return ID with multiple results in array).
This is the current function I do:
public static function getMedia($em, $entity, $id = NULL)
{
$dql = 'SELECT m.id, m.url, m.nb, m.lang
FROM iMT\Entity\Media m INDEX BY m.id JOIN iMT\Entity\\' . $entity . ' r WITH m.id = r.id';
if($id) {
$dql .= " WHERE r.id = ?1";
}
$q = $em->createQuery($dql);
if($id) {
$q->setParameter(1, $id);
}
return $q->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
}
Which returns:
array (size=44)
479600 =>
array (size=4)
'id' => int 479600
'url' => string 'pois/479600/Nonna.JPG' (length=48)
'nb' => null
'lang' => string 'fr' (length=2)
479615 =>
array (size=4)
'id' => int 479615
'url' => string 'pois/479615/Tramways.jpg' (length=51)
'nb' => null
'lang' => string 'fr' (length=2)
479580 =>
array (size=4)
'id' => int 479580
'url' => string 'pois/479580/ATLAS.jpg' (length=48)
'nb' => null
'lang' => string 'fr' (length=2)
479581 =>
array (size=4)
'id' => int 479581
'url' => string 'pois/479581/P'tit_sushi.jpg' (length=54)
'nb' => null
'lang' => string 'fr' (length=2)
However, I need the output to be:
array (size=44)
479600 =>
array (size=2)
array (size=4)
'id' => int 479600
'url' => string 'pois/479600/Nonna.JPG' (length=48)
'nb' => null
'lang' => string 'fr' (length=2)
array (size=4)
'id' => int 479600
'url' => string 'pois/479600/OtherPic.JPG' (length=48)
'nb' => null
'lang' => string 'fr' (length=2)
Would I need to create my own AbstractQuery::HYDRATE_ARRAY or is there something available that does what I need?
I'm using the result by checking if it contains a key that matches the ID of the current item (e.g. if(isset($data[$item])) // where $item = 479600 then output images), maybe there's a better way to check for the results?
EDIT
I've updated my function to return:
$result = $q->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
$data = array();
$count = count($result);
for($i = 0; $i < $count; $i++) {
if(!isset($data[$result[$i]['id']])) {
$data[$result[$i]['id']] = array(
$result[$i]
);
} else {
$data[$result[$i]['id']][] = $result[$i];
}
}
return $data;
Which returns something more to what I want:
array (size=44)
479600 =>
array (size=1)
0 =>
array (size=4)
'id' => int 479600
'url' => string 'pois/479600/Nonna.JPG' (length=48)
'nb' => null
'lang' => string 'fr' (length=2)
479577 =>
array (size=2)
0 =>
array (size=4)
'id' => int 479577
'url' => string 'pois/479577/AOMC.JPG' (length=47)
'nb' => null
'lang' => string 'fr' (length=2)
1 =>
array (size=4)
'id' => int 479577
'url' => string 'pois/479577/Buffet AOMC.jpg' (length=54)
'nb' => null
'lang' => string 'fr' (length=2)
Can this be improved? Is there any Doctrine functions that can help, or should I leave my for() loop?

The problem with using INDEX BY together with a JOIN is that the result that doctrine gives you might not contain all data that's fetched from the database.
In your case the database might return multiple rows containing the same value for m.id (because of the JOIN). But each subsequent row containing the same value for m.id will overwrite the previous one (because of the INDEX BY m.id).
Doctrine does not come with a hydrator that can solve this problem out of the box. You shall indeed need to implement your own. Read more about creating custom hydration modes.
Alternative
Another solution would be to not use INDEX BY in this case.
You could write a repository method that translates the result given by Doctrine to the array you want to have. Other parts of your application can then call that repository method.
This is probably easier than creating a custom hydration mode.
Update
The translation can look like this:
$data = array();
foreach ($q->getArrayResult() as $row) {
if (!isset($data[$row['id']])) {
$data[$row['id']] = array();
}
$data[$row['id']][] = $row;
}
return $data;

Related

MYSQL PHP Array grouping

Having trouble wrapping my head around this conceptually. Still new to this. Basically I have this return from my database :
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 =>
What I'm trying to do with PHP is create an object/array that I can work with that displays these items like
AMLP 1 found on dates 2019-09-13
ARCC 2 found on dates 2019-09-13, 2019-09-12
In the end I would display these in a table, but conceptually this is what I'm trying to do.
I've tried creating an array in my foreach I use to display this information in a table, but I was thinking about it and it's probably better to just use the same query data and break it down separately.
So I'd like to create an array like :
Array
(
[1] => Array
(
[id] => 1
[symbol] => ARCC
[dates] => Array
(
[3] => Array
(
2019-09-13
2019-09-12
)
)
)
)
Consider your array is $arrDates. If you want to access properties like object properties
$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 to get the desired subpart of symbol
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;
}

CakePHP: Load name field of related model on view

Guys I have a simple but boring question...
I have the following scenario:
Solicitation -> HasMany -> Destiny
Destiny -> BelongsTo -> City
My problem is on the view, I want to retrieve the City name instead of the city_id and I can't figure out.
Here is my Result:
array (size=12)
'Solicitation' =>
array (size=32)
'id' => string '25' (length=2)
'Destiny' =>
array (size=2)
0 =>
array (size=3)
'id' => string '3' (length=1)
'solicitation_id' => string '25' (length=2)
'city_id' => string '4382' (length=4)
1 =>
array (size=3)
'id' => string '4' (length=1)
'solicitation_id' => string '25' (length=2)
'city_id' => string '4350' (length=4)
How can I retrieve the city name on the view?
Here's my controller:
public function mySolicitations()
{
$this->Solicitation->recursive = 1;
$person_id = $this->Auth->user('id');
$conditions = array(
'Solicitation.created_by' => $person_id
);
$this->set(array(
'data' => $this->paginate('Solicitation', $conditions, array('Solicitation.id' => 'DESC')),
'title_for_layout' => 'My Solicitations'
));
}
Is there a problem with my relation?
Thanks in advance.
There are two ways:
Change your model recursive value to 2.
$this->Solicitation->recursive = 2;
The drawback of using this is when you have quite a few associations involved, it'll retrieve a lot of unwanted unnecessary data.
You can use "Containable" Behavior here.
$this->Solicitation->Behaviors->load("Containable");
And specify the model names that you want to retrieve:
$this->Solicitation->contain(array(
"Destiny", "Destiny.City"
)
);
Then add your code:
$conditions = array(
'Solicitation.created_by' => $person_id
);
$this->set(array(
'data' => $this->paginate('Solicitation', $conditions, array('Solicitation.id' => 'DESC')),
'title_for_layout' => 'My Solicitations'
));
If you debug, you'll certainly find the "City" index within each Destiny sub arrays.
Hope this helps.
Peace! xD

Building a form dynamically with Codeigniter and Active Record queries

Model
function get_prices()
{
$table_by_product = 'printer_businesscards'; //replace with URI Segment
//Get all the columns in the table set by the page URI of $table_by_product variable
$get_all_col_names = $this->db->list_fields($table_by_product);
//Loop through the column names. All names starting with 'O_' are optional fields for the
//current product. Get all Distinct values and create a radio button list in form.
foreach ($get_all_col_names as $key => $value) {
//get all o_types for the product by column name
if ($all_O_types = preg_match('/O_/', $value))
{
$O_types = array($value);
foreach ($O_types as $O) {
//echo $O;
$this->db->select($O);
$this->db->distinct();
$qO = $this->db->get($table_by_product);
$qO_Array = $qO->result_object();
}
}
//Get all x_types for the product by column name. All 'X_' types are specific product options.
//Create a dropdown menu with all DISTINCT product options.
if ($all_X_types = preg_match('/X_/', $value))
{
$X_types = array($value);
foreach ($X_types as $X) {
//echo $X;
$this->db->select($X);
$this->db->distinct();
$qX = $this->db->get($table_by_product);
$qX_Array = $qX->result_object();
}
}
}
return array($qX_Array,$qO_Array);
}
}
So each product has different options but all products options are prefixed by "X_" or "O_". I need to get the DISTINCT values of each COLUMN of "X_" and "O_" and in any VIEW I need to build a form with these values. Here is a look at the array:
array (size=3)
0 =>
object(stdClass)[19]
public 'X_SIZE' => string '1.75x3' (length=6)
1 =>
object(stdClass)[20]
public 'X_SIZE' => string '1.75x3.5(slim)' (length=14)
2 =>
object(stdClass)[21]
public 'X_SIZE' => string '2x3' (length=3)
array (size=3)
0 =>
object(stdClass)[17]
public 'X_PAPER' => string '14ptGlossCoatedCoverwithUV(C2S)' (length=31)
1 =>
object(stdClass)[18]
public 'X_PAPER' => string '14ptPremiumUncoatedCover' (length=24)
2 =>
object(stdClass)[24]
public 'X_PAPER' => string '16ptDullCoverwithMatteFinish' (length=28)
array (size=2)
0 =>
object(stdClass)[23]
public 'X_COLOR' => string '1000' (length=4)
1 =>
object(stdClass)[22]
public 'X_COLOR' => string '1002' (length=4)
array (size=4)
0 =>
object(stdClass)[20]
public 'X_QTY' => string '100' (length=3)
1 =>
object(stdClass)[21]
public 'X_QTY' => string '250' (length=3)
2 =>
object(stdClass)[17]
public 'X_QTY' => string '500' (length=3)
3 =>
object(stdClass)[19]
public 'X_QTY' => string '1000' (length=4)
array (size=3)
0 =>
object(stdClass)[25]
public 'O_RC' => string 'YES' (length=3)
1 =>
object(stdClass)[26]
public 'O_RC' => string 'NO' (length=2)
2 =>
object(stdClass)[27]
public 'O_RC' => string 'NA' (length=2)
My current MODEL is only returning X_QTY and O_RC to my view.
What am I doing incorrectly?
You are only returning the last result object of each; ie, you are setting
$qO_Array = $qO->result_object();
to a variable, and it should be:
$qO_Array[] = $qO->result_object();
to get all of them
BTW - do you have a specific reason for calling result_object() instead of the usual result() or result_array()? It's not necessarily wrong, but I wonder if you are doing it intentionally?

accessing objects data in an array

If someone has some help/advice about how to tackle this problem I'd really appreciate it. I've created a metasearch engine that for all intensive purposes works ok, but my code is pretty breakable! The following code is a sample var_dump of the array of objects - searchEngineArray. I want to store the results of each search engine in an array, but it needs to be in some kind of generic loop that (A). won't break if one search engine doesn't return results and (B). can easily accommodate additional search engines.
object(BingSearch)[1]
private 'formatted_query' => string 'england' (length=7)
public 'search_results' =>
array
0 =>
array
'title' => string 'England - Wikipedia, the free encyclopedia' (length=42)
'url' => string 'http://en.wikipedia.org/wiki/England' (length=36)
'score' => int 30
1 =>
array
'title' => string 'BBC News - England' (length=18)
'url' => string 'http://www.bbc.co.uk/news/england/' (length=34)
'score' => int 28
2 =>
array
'title' => string 'The FA - The website for the English football association, The FA ...' (length=69)
'url' => string 'http://www.thefa.com/' (length=21)
'score' => int 26
object(BlekkoSearch)[2]
private 'formatted_query' => string 'england' (length=7)
public 'search_results' =>
array
0 =>
array
'title' => string '<strong>England</strong> - Wikipedia' (length=36)
'url' => string 'http://en.wikipedia.org/wiki/England' (length=36)
'score' => int 25
1 =>
array
'title' => string 'The official site of Visit <strong>England</strong> - The <strong>England</strong> Tourist Board' (length=96)
'url' => string 'http://www.enjoyengland.com/' (length=28)
'score' => int 23
2 =>
array
'title' => string 'Arts Council <strong>England</strong> - Arts Council' (length=52)
'url' => string 'http://www.artscouncil.org.uk/' (length=30)
'score' => int 21
object(EntirewebSearch)[3]
private 'formatted_query' => string 'england' (length=7)
public 'search_results' =>
array
0 =>
array
'title' => string 'Arts Council England | Arts Council' (length=35)
'url' => string 'http://www.artscouncil.org.uk/' (length=30)
'score' => int 20
1 =>
array
'title' => string 'Sport England ' (length=14)
'url' => string 'http://www.sportengland.org/' (length=28)
'score' => int 18
2 =>
array
'title' => string 'Bank of England ' (length=16)
'url' => string 'http://www.bankofengland.co.uk/' (length=31)
'score' => int 16
I have it working to an extent, but its just not good code really. Heres how it works at the moment, has anyone got any ideas on how to create a more generic way of storing the information?
public function storeResults($searchEnginesArray)
{
//The following is very bad
//$blekko_Array = "";
//$bing_Array = "";
//$entireweb_Array = "";
for($x=0; $x<sizeof($searchEnginesArray); $x++)
{
var_dump($searchEnginesArray[$x]);
/*switch ($searchEnginesArray[$x]->getEngineName()) {
case "Bing":
$bing_Array = $searchEnginesArray[$x]->getResults();
break;
case "Blekko":
$blekko_Array = $searchEnginesArray[$x]->getResults();
break;
case "Entireweb":
$entireweb_Array = $searchEnginesArray[$x]->getResults();
break;
default:
echo "Error: Unexpected Search Engine : ".$searchEnginesArray[$x]->getEngineName(). " Expects [Bing/Blekko/Entireweb]";
} */
}
<?
public function storeResults($searchEnginesArray) {
for($i=0;$i<count($searchEnginesArray);$i++) {
$result = $searchEnginesArray[$i]->getResults();
// Ignore engines with empty results
if( !empty($result) ) {
$results[ $searchEnginesArray[$i]->getEngineName() ] = $result;
}
}
// create an array for every engine, are you sure it's needed?
extract($results, EXTR_SKIP);
}
?>

php array count

I have a var dump of my sql query which return the following
I wanna to count in the array below that how many rows of myID = 5 are there. How would I do that. I am using php. Thanks in advance
array
0 =>
object(stdClass)[17]
public 'myID' => string '5' (length=1)
public 'data' => string '123' (length=3)
1 =>
object(stdClass)[18]
public 'myID' => string '5' (length=1)
public 'data' => string '123' (length=3)
2 =>
object(stdClass)[19]
public 'relativeTypeID' => string '2' (length=1)
public 'data' => string '256' (length=3)
3 =>
object(stdClass)[20]
public 'myID' => string '4' (length=1)
public 'data' => string '786' (length=3)
object(stdClass)[21]
public 'myID' => string '4' (length=1)
public 'data' => string '786' (length=3)
Do you always have the same value of data for the same myID? In other words, is data functionally dependant on myID?
If so, you can get the database to do this for you:
SELECT myID, data, COUNT(*) AS cnt
FROM (your query here)
GROUP BY myID, data
This would give you results like the following:
myID data cnt
'5' '123' 3
'2' '256' 1
'4' '786' 2
Or, you can use a foreach statement, like:
$count = 0;
foreach($arr as $item)
{
// Given that your item is an stdClass Object you access its property with "->"
// if an array $item["myID"] instead
if ( $item->myID == '4' )
{
$count ++;
}
}

Categories