read laravel object and get data - php

I am trying to read laravel object and assign that into a new variable I have no idea to do that please someone help
THIS IS MY FUNCTION
public function nextToJumpGrs(CompetitionService $competitionService, CachedEventResourceService $cachedEventResourceService, ConfigurationRepositoryInterface $configurationRepository,MarketRepository $marketTypeRepository)
{
$nextToJump = $cachedEventResourceService->nextToJump();
$markets=array();
$config = $configurationRepository->getConfigByName('sports_settings', true);
$competitions = $competitionService->getCompetitionsByN2JEventResourcesGrs($nextToJump->slice(0, array_get($config, 'next_to_jump_events')));
return $competitions;
}
}
this is what $competitions return
I want to read those markets[] and products[] and assign to another variable please someone help

Just typecast it
$array = (array) $competitions;
Then loop through it
$markets = [];
$products = [];
foreach($array as $item) {
dump($item['id']);
dump($item['name']);
//...
foreach($item['events'] as $event) {
dump($event['id']);
dump($event['name']);
//...
$markets[$item['id']][] = $event['markets'];
foreach($event['markets'] as $market) {
dump($market['id']);
dump($market['name']);
dump($market['line']);
//...
}
$products[$item['id']][] = $event['products'];
foreach($event['products'] as $product) {
dump($product['product_id']);
dump($product['bet_type']);
dump($product['product_code']);
//...
}
}
}

Related

Add object to php array in symfony

I currently have 2 classes:
workerListClass
workerClass
The workerListClass gets a list of work with ids from database. For each of these the workerClass is called
foreach ($query as $value) {
$result = $this->worker->getWorkerById($value['ID']); // DB Call to get additional data
$this->addData($result);
vardumper::dump($result->getId());
// This results in 1031 and 1528
}
addDate is very simple
public function addData(workerClass $worker): void
{
$this->data[] = $worker;
}
But if i try to go through this array something strange happens
$result = $this->workerListClass->getWorker()->getData();
foreach ($result as $worker) {
vardumper::dump([
$worker->getId() // this outputs 1528 twice!!!
]);
}
getData does nothing special
public function getData(): array
{
return $this->data;
}
Can someone help me why this outputs 1528 twice?
Problem found. The issues was that the same class was changed and not a new class was setup.
Using clone on the workerlist helped fixing this:
foreach ($query as $value) {
$localWorker = clone $this->worker; //starts a new instance so that it is not referenced
$result = $localWorker->getWorkerById($value['ID']);
$this->addData($result);
vardumper::dump($result->getId());
}

My function won't store the highest value in the variable in Laravel

I'm trying to get this field from my Mongodb, but I don't know why I get stored in my var only the first value (that isn't the highest) and the correct one.
public function globalChartGet() {
$firstInChart = 0;
$users = User::all();
foreach ($users as $user) {
if ($user->points > $firstInChart) {
$firstInChart = $user->points;
}
}
}
Just do this
$highest = $users->max('points');
Hope it helps

PHP out of memory with CDataProviderIterator (Yii)

I am having an out of memory issue with my PHP script on the Yii framework. I've tried to do quite a bit of debugging. I'm using a CDataProviderIterator because the Yii documentation says this about it:
For example, the following code will iterate over all registered users (active record class User) without running out of memory, even if there are millions of users in the database.
This code iterates over around 1.5 million records and it runs out of memory in its attempt. I'm looking for any kind of help of why it might be doing this. Thanks!
public function foo($model, $relations) {
$dataProvider = new CActiveDataProvider($model, array('criteria' => $model->dbCriteria));
$iterator = new CDataProviderIterator($dataProvider, 200);
$this->modelsToArray($iterator, $relations, $model_as_array = array());
}
public function modelsToArray($model, $relations, $model_as_array = array()) {
$preparedRelations = $this->prepareRelations($relations);
if (is_null($model))
{
return array();
}
$model_as_array = array();
if (get_class($model) === 'CDataProviderIterator') {
foreach ($model as $row) {
$model_as_array[] = $this->modelsToArrayHelper($preparedRelations, $row);
}
}
else {
$model_as_array[] = $this->modelsToArrayHelper($preparedRelations, $model);
}
return $model_as_array;
}
private function modelsToArrayHelper($relations, $listOfModels) {
$listOfArrayModels = array();
if(!is_array($listOfModels)){
return $this->modelToArrayHelper($listOfModels, $relations);
}
foreach ($listOfModels as $index => $model)
{
$listOfArrayModels[$index] = $this->modelToArrayHelper($model, $relations);
}
return $listOfArrayModels;
}
private function modelToArrayHelper($model, $relations){
$model_as_array = $this->processAttributes($model);
foreach ($relations as $relationIndex => $relation)
{
$relationName = is_string($relationIndex) ? $relationIndex : $relation;
if(empty($model->$relationName))
continue;
if ($model->relations()[$relationName][0] != CActiveRecord::STAT)
{
$subRelations = is_array($relation) ? $relation : array();
$model_as_array[$relationName] = $this->modelsToArrayHelper($subRelations, $model->$relationName);
}
else
{
$model_as_array[$relationName] = $model->$relationName;
}
}
return $model_as_array;
}
i believe you are trying to convert the CDataProviderIterator to a Php array.
so for placing the array you need more memory
ini_set('memory_limit', '-1');
this sets the use of ram to max usage
ini_set('memory_limit', '512M');
this sets the ram usage to 512 Mb
Can you make your code like this just to make sure you are not using too much ram
public function foo($model, $relations) {
$dataProvider = new CActiveDataProvider($model, array('criteria' => $model->dbCriteria));
$iterator = new CDataProviderIterator($dataProvider, 200);
$preparedRelations = $this->prepareRelations($relations);
foreach ($iterator as $row) {
print_r ($this->modelsToArrayHelper($preparedRelations, $row));
}
}
and

php pass array to function as separate variables

i need to know how to pass an array to a function as separate variables, for instance,
function myfunction($var, $othervar) {
}
$myarray = array('key'=>'val', 'data'=>'pair');
here is where I am running into problems, the following doesn't seem to work:
$return = myfunction(extract($myarray));
it should, if I understand correctly, basically be the same as
$return = myfunction($key, $data);
where $key='val' and $data='pair'
can anyone please explain this to me.
If I am understanding your question right then try this
$return = myfunction($myarray["key"],$myarray["data"]);
here we are simply passing the associative array as arguments.
public function get($key=null, $function='', array $vars=array()) {
if ($key==null || !array_key_exists($key, $this->_obj)) {
return null;
}
var_dump($vars);
if (!empty($function)) {
return $this->_obj[$key]->$function(array_walk($vars));
// return call_user_func_array(array(get_class($this->_obj[$key]), $function), $vars);
// return $this->_obj[$key]->$function(extract($vars));
}
return $this->_obj[$key];
}
public function get($key=null, $function='', array $vars=array()) {
if ($key==null || !array_key_exists($key, $this->_obj)) {
return null;
}
if (!empty($function)) {
return call_user_func_array(array($this->_obj[$key], $function), $vars);
}
return $this->_obj[$key];
}
$registry = Registry_Object::Singleton();
//...later on
$registry = $GLOBALS['registry'];
$registry->set('Content', new Content($_SERVER['REQUEST_URI']));
$id = $registry->get('Content', 'GetIdFunc');
$registry->set('DB', 'Database');
$query = $registry->get('DB', 'Read', array("SELECT TITLE, CONTENT FROM APP_CONTENT WHERE ID=$id"));
print '<h1>'.$query[0]['TITLE'].'</h1>';
print Template_Helper::TPL_Paragraphs($query[0]['CONTENT']);
thanks all

PHP: Modifying array with unknown structure at runtime; what is the most elegant solution?

PROBLEM
I have a function that takes in a nested array where the structure and nesting of the array is unknown at run-time. All that is known is some of the target fieldnames and desired values of some of the leafs.
QUESTIONS
1) I am hoping to modify this unknown structure and still have the code be readable and easily understood by fellow programmers. What (if any) solution will allow me to do things like this in PHP?
// Pseudo-code for things I would like to be able to do
// this is kinda like the same thing as XPATH, but for native PHP array
// find *every* fname with value of "Brad" and change it to "Brian"
$mydata->find_all('*:fname')->where_value_eq('Brad')->set_equal_to('Brian');
// find *the first* fave_color and set it to "Green"
$mydata->find('*:fave_color')->get(0)->set_equal_to('Green');
2) If there is nothing out there that will let me do this, is there something, anything, that at least comes close to the spirit of what I am hoping to accomplish here?
SAMPLE ARRAY
$mydata = array(
'people' => array(
array('fname'=>'Alice'),
array('fname'=>'Brad'),
array('fname'=>'Chris'),
),
'animals' => array(
array('fname'=>'Dino'),
array('fname'=>'Lassie'),
array('fname'=>'Brad'),
),
'settings' => array(
'user_prefs'=>array(
'localhost'=>array(
'fave_color'=>'blue',
),
),
),
'places' => array(
array('state'=>'New york',
'cities'=>array(
'name'=>'Albany',
'name'=>'Buffalo',
'name'=>'Corning',
),
'state'=>'California',
'cities'=>array(
'name'=>'Anaheim',
'name'=>'Bakersfield',
'name'=>'Carlsbad',
),
),
),
);
Although I maintain that you should stick with explicit manipulation as in my previous answer, boredom and intrigue got the better of me ;)
It probably has holes (and clearly lacks docs) but if you insist on this route, it should get you started:
class Finder {
protected $data;
public function __construct(&$data) {
if (!is_array($data)) {
throw new InvalidArgumentException;
}
$this->data = &$data;
}
public function all() {
return $this->find();
}
public function find($expression = null) {
if (!isset($expression)) {
return new Results($this->data);
}
$results = array();
$this->_find(explode(':', $expression), $this->data, $results);
return new Results($results);
}
protected function _find($parts, &$data, &$results) {
if (!$parts) {
return;
}
$currentParts = $parts;
$search = array_shift($currentParts);
if ($wildcard = $search == '*') {
$search = array_shift($currentParts);
}
foreach ($data as $key => &$value) {
if ($key === $search) {
if ($currentParts) {
$this->_find($currentParts, $value, $results);
} else {
$results[] = &$value;
}
} else if ($wildcard && is_array($value)) {
$this->_find($parts, $value, $results);
}
}
}
}
class Results {
protected $data;
public function __construct(&$data) {
$this->data = $data;
}
public function get($index, $limit = 1) {
$this->data = array_slice($this->data, $index, $limit);
return $this;
}
public function set_equal_to($value) {
foreach ($this->data as &$datum) {
$datum = $value;
}
}
public function __call($method, $args) {
if (!preg_match('/^where_?(key|value)_?(eq|contains)$/i', $method, $m)) {
throw new BadFunctionCallException;
}
if (!isset($args[0])) {
throw new InvalidArgumentException;
}
$operand = $args[0];
$isKey = strtolower($m[1]) == 'key';
$method = array('Results', '_compare' . (strtolower($m[2]) == 'eq' ? 'EqualTo' : 'Contains'));
$ret = array();
foreach ($this->data as $key => &$datum) {
if (call_user_func($method, $isKey ? $key : $datum, $operand)) {
$ret[] = &$datum;
}
}
$this->data = $ret;
return $this;
}
protected function _compareEqualTo($value, $test) {
return $value == $test;
}
protected function _compareContains($value, $test) {
return strpos($value, $test) !== false;
}
}
$finder = new Finder($mydata);
$finder->find('*:fname')->where_value_eq('Brad')->set_equal_to('Brian');
$finder->find('*:fave_color')->get(0)->set_equal_to('Green');
$finder->find('places:*:cities:*:name')->where_value_contains('ba')->set_equal_to('Stackoton');
print_r($mydata);
There's certainly no native solution for this and the syntax is rather strange. If you want the code to "be readable and easily understood by fellow programmers" please stick to methods that we're used to working with ;)
foreach ($mydata as $type => &$data) {
foreach ($data as &$member) {
if (isset($member['fname']) && $member['fname'] == 'Brad') {
$member['fname'] = 'Brian';
}
}
}
It's admittedly more verbose, but there's much less chance of confusion.

Categories