insert element on array on private function - php

How can insert element into final position of array this array is on a private function??
private function getData()
{
return array(
1 => array(
'open_cookie_id' => 1,
'text' => 'I may throw up on ya',
'who' => 'Leonard McCoy',
),
2 => array(
'open_cookie_id' => 2,
'text' => 'I think these things are pretty safe.',
'who' => 'James T. Kirk'
),
3 => array(
'open_cookie_id' => 3,
'text' => 'Well, I hate to break this to you, but Starfleet operates in space.',
'who' => 'James T. Kirk'
),
4 => array(
'open_cookie_id' => 4,
'text' => 'Yeah. Well, I got nowhere else to go. The ex-wife took the whole damn planet in the divorce. All I got left is my bones.',
'who' => 'Leonard McCoy'
),
5 => array(
'open_cookie_id' => 5,
'text' => 'If you eliminate the impossible, whatever remains, however improbable, must be the truth.',
'who' => 'Spock'
)
);
}
How to insert the element 6 , 7, 8 etc to final array on these function private from other function
from this function:
/**
* Create a resource
*
* #param mixed $data
* #return ApiProblem|mixed
*/
public function create($data)
{
//return new ApiProblem(405, 'The POST method has not been defined');
//return $this->create($data) ;
$adapter = new ArrayAdapter($this->getData());
$adapter2 = Array
(
$data->open_cookie_id => array(
'open_cookie_id'=>$data->open_cookie_id ,
'text' =>$data->text,
'who' => $data->who
)
);
$adapter2_converted = new ArrayAdapter($adapter2);
//operation for merge two ArayAdapter ($adapter+$adapter2_convert)
// $collection = new OpenCookieCollection($final_adapter);
//return $collection;
}
I'm using php zend framework and apigility.

The function is private not the array so you can safely work with your returned array. Do notice that $adapter is a ArrayAdapter data type, not a simple array so you can't simple push.
My suggestion is to add a method to your ArrayAdapter that uses PHP array_push() to add your array to your ArrayAdapter data structure and use like this:
$adapter->pushArray($adapter2);

I think this is the line where you're actually calling the private method getData():
$adapter = new ArrayAdapter($this->getData());
If all you need as a result is an array with some extra elements added to it, you can do something like this:
$data = $this->getData();
$data[] = 'more data';
$data[] = 'even more data';
$adapter = new ArrayAdapter($data);

Related

Include class name when using Doctrine 2 array hydration

In Doctrine 2 is there a way to get the array hydration mode to include the class name of the relevant entity in the output, so instead of:
array(
'id' => 1,
'name' => 'test',
// ...
);
You get:
array(
'__class' => 'MyProject\MyClass',
'id' => 1,
'name' => 'test',
// ...
);
I know the Doctrine\ORM\Internal\Hydration\ArrayHydrator class has access to the relevant information, but I'm trying to work out if this can be done without re-implementing the entire ArrayHydrator?
So creating a custom hydrator that extends ArrayHydrator and overriding the gatherRowData method with this is one potential solution:
protected function gatherRowData(array $data, array &$id, array &$nonemptyComponents)
{
$rowData = parent::gatherRowData($data, $id, $nonemptyComponents);
foreach ($rowData['data'] as $dqlAlias => $data) {
$class = $this->_rsm->aliasMap[$dqlAlias];
$meta = $this->getClassMetadata($class);
if ($meta->discriminatorMap) {
$class = $meta->discriminatorMap[$data[$meta->discriminatorColumn['name']]];
}
$rowData['data'][$dqlAlias]['__CLASS__'] = $class;
}
return $rowData;
}
Be interested to know if there's a better way?

foreach to get the array index results in PHP

I got the following parameters as a response from SOAP client. But i only want few to show as a result. I am getting the results properly but its only for 1 vehicle and i have more than 1 vehicles. So i dont know how to loop to get the results.
Output for 1 vehicle
array (size=5)
'SchwackeCode' => int 10130969
'WE_Number' => int 19373134
'HSN' => string '0005' (length=4)
'TSN' => string 'AMP' (length=3)
'VIN' => string '12345678901472583' (length=17)
Code:
$client = new SoapClient($wsdl, $options);
$result = $client->getVehicleValuation($params);
$return = array(
'SchwackeCode' => $result->vehicle->SchwackeCode,
'WE_Number' => $result->vehicle->WE_Number,
'HSN' => $result->vehicle->HSN,
'TSN' => $result->vehicle->TSN,
'VIN' => $result->vehicle->Ident_Number,
'WE_Number' => $result->vehicle->WE_Number
);
return $return;
ok, then just try this simple code,
$cnt=0;
$arr=Array('SchwackeCode','WE_Number','HSN','TSN' );
foreach($result->Vehicle[$cnt]->Customer[0] as $key=>$val)
{
if(in_array($key,$arr)
{
your_piece of code;
}
$cnt++;
}
Didnt tested this code, but hopefully it will work. :)

How to: array_push into multiple array with a strict hierarchy?

I'm trying to build an archive-class for my firebird database. And I have the following problem a couple of times already:
I want to construct an array-structure like that:
/**
* #var [] stores the success log of all db operations
*
* $_log = Array(
* (string) [DATA_SOURCE] => Array(
* (int) [0] => Array(
* (string) [id] => (int) 32,
* (string) [action] => (string) "update/insert/delete",
* (string) [state] => (int) 1,
* (string) [message] => (string) "success/error",
* )
* )
* )
*/
private $_log = array();
MY 1. TRY:
// push result to log array
array_push(
$this->_log,
array(
"archive" => array(
"id" => $row["ID"],
"action" => "update",
"state" => $success,
),
)
);
RESULTS IN:
Array(
[0] => Array(
[archive] => Array(
[id] => 32
[action] => update
[state] => 1
)
)
)
That's not exactly what i want. I want the "data-source"-key here "archive" in front of the pushed entry [0].
MY 2nd TRY
array_push(
$this->_log["archive"],
array(
"id" => $row["ID"],
"action" => "update",
"state" => $success,
)
);
RESULTS IN
<br />
<b>Warning</b>: array_push() expects parameter 1 to be array, null given in <b>/Users/rsteinmann/web/intranet/pages/firebird/ArchiveTables.php</b> on line <b>238</b><br />
I'm a bit helpless with this task. I also tried to find anything on google or stackoverflow but there was nothing really useful.
I would be so glad if someone could help me with that!
Thank you,
Raphael
$this->log['archive'][] = array('id' => ...);
This is the sanest way to do it. PHP will create any non-existing keys (like archive) for you. array_push on the other hand is a function call and requires its arguments to already exist, it can't create a non-existing archive key for you. You'd have to do that before you call the function.
array_push is mostly useful if you need to push several arguments at once (array_push($arr, $a, $b, $c)), otherwise $arr[] = $a is the generally preferred and officially recommended syntax.

PHP map named array to another named array

I have the following code for generating a new array:
$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
function generateLanguageRules($language)
{
return ["seatsAllocatedFor$language"=>"numeric|max:300"];
}
array_map('generateLanguageRules', $languages);
//Output:
array(
0 => array(
'seatsAllocatedForFrench' => 'numeric|max:300'
),
1 => array(
'seatsAllocatedForSpanish' => 'numeric|max:300'
),
2 => array(
'seatsAllocatedForGerman' => 'numeric|max:300'
),
3 => array(
'seatsAllocatedForChinese' => 'numeric|max:300'
)
)
I'm wondering if there is an easier way to output a flat array, instead of a nested one? I'm using Laravel. Are there maybe some helper functions that could do this?
UPDATE:
One possible Laravel specific solution:
$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
$c = new Illuminate\Support\Collection($languages);
$c->map(function ($language){
return ["seatsAllocatedFor$language"=>"numeric|max:300"];
})->collapse()->toArray();
I dont know if laravel has a built-in method for that, (haven't used it yet). But alternatively, you could use RecursiveArrayIterator in conjunction to iterator_to_array() to flatten it and assign it. Consider this example:
$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
function generateLanguageRules($language) {
return ["seatsAllocatedFor$language"=>"numeric|max:300"];
}
$data = array_map('generateLanguageRules', $languages);
$data = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)));
echo "<pre>";
print_r($data);
echo "</pre>";
Sample Output:
Array
(
[seatsAllocatedForFrench] => numeric|max:300
[seatsAllocatedForSpanish] => numeric|max:300
[seatsAllocatedForGerman] => numeric|max:300
[seatsAllocatedForChinese] => numeric|max:300
)

Array with colon

SOLVED:
getDimesions() ... google has made a type error.. LOL
facing some problems with array with colon in the name,
my $result is containing
gapiReportEntry::__set_state(array(
'metrics' =>
array (
'uniquePageviews' => 1523,
),
'dimensions' =>
array (
'pagePath' => '/',
'pageTitle' => 'Eventyrgolf',
'source' => 'google',
'medium' => 'organic',
'campaign' => '(not set)',
),
))
gapiReportEntry::__set_state(array(
'metrics' =>
array (
'uniquePageviews' => 210,
),
'dimensions' =>
array (
'pagePath' => '/dk/greenfee-og-banen-8/',
'pageTitle' => 'Greenfee og Banen',
'source' => 'google',
'medium' => 'organic',
'campaign' => '(not set)',
),
))
But some how i cannot get the "dimensions:private"... What to do?
I tried print_r():
$result->{"dimensions:private"}
$result['dimensions:private']
$result->dimensions
Full code:
$ga->requestReportData($profileId, $dimensions, $metrics, $sort, null, $fromDate, $toDate, 2, 30);
foreach ($ga->getResults() as $result) {
print_r($result->dimensions);
}
your $result is not an array, but an object. if you var_dump an object, you see it's contents, which in your case is an object with 2 private variables metrics and dimensions. To access these, the object probably has some accessors:
$result->getMetrics();
$result->getDimensions();
The dimensions property of $result object is private. That means it can be accessed only by objects of the same class.
Check if your gapiReportEntry class contains so called getter, that is a mathod which can access the property dimensions and return it's value to you. Look for something like getDimensions.
Read more about class field visibility here http://pl1.php.net/manual/en/language.oop5.visibility.php
EDIT
If your gapiReportEntry is a google analitics report, then this docs says that there is a getDimensions() method, so just call
$result->getDimensions();
EDIT #2
As suggested in comment, the class seems to have misspeled method name. The actual method is named getDim**es**ions:
$result->getDimesions();
Private is a reserved keyword in PHP and you should be scaping colon ":" with a backslash before it.

Categories