I have an Array Object which I would like to print as an Associative Array
<?php
require_once(dirname(__FILE__) . '/HarvestAPI.php');
/* Register Auto Loader */
spl_autoload_register(array('HarvestAPI', 'autoload'));
$api = new HarvestAPI();
$api->setUser( $user );
$api->setPassword( $password );
$api->setAccount( $account );
$api->setRetryMode( HarvestAPI::RETRY );
$api->setSSL(true);
$result = $api->getProjects(); ?>
It should print something like this.
Array ( [] => Harvest_Project Object (
[_root:protected] => project
[_tasks:protected] => Array ( )
[_convert:protected] => 1
[_values:protected] => Array (
[id] => \
[client-id] => -
[name] => Internal
[code] =>
[active] => false
[billable] => true
[bill-by] => none
[hourly-rate]=>-
How can I achieve this?
Update
I tried doing a varexport. But it gives something like this
Harvest_Result::__set_state(array( '_code' => 200, '_data' => array ( 5443367 => Harvest_Project::__set_state(array( '_root' => 'project', '_tasks' => array ( ), '_convert' => true, '_values' => array ( 'id' => '564367', 'client-id' => '2427552', 'name' => 'Internal', 'code' => '', 'active' => 'false', 'billable' => 'tr
This is not what I am looking for. The object should clearly list the fields it has.
If there's a need to get visibility types as well in the string representation of the object's properties, it can be solved quite simply with ReflectionClass:
$arrayObj = new Harvest_Project();
$reflection = new \ReflectionClass($arrayObj);
$objStr = '';
$properties = $reflection ->getProperties();
foreach ($properties as $property)
{
if ($property->isPublic()) $propType = 'public';
elseif ($property->isPrivate()) $propType = 'private';
elseif ($property->isProtected()) $propType = 'protected';
else $propType = 'static';
$property->setAccessible(true);
$objStr .= "\n[{$property->getName()} : $propType] => " . var_export($property->getValue($arrayObj), true) .';';
}
var_dump($objStr);
The output looks like this:
[_foobar : private] => 42;
[_values: protected] => array (
0 => 'foo',
1 =>
array (
0 => 'bar',
1 => 'baz',
),
);
Warning getProperties might not get inherited properties depending on the PHP version; in this case see examples of how to recursively get them all here.
Related
I am trying to add my data to my array inside my foreach loop.
I have almost done it successfully, except the array is too in-depth.
It's showing array->array->{WHAT I WANT}
When I need array->{WHAT I WANT}
Example, I'm needing it to be like:
Array
(
[home] => Array
(
[0] => Dashboard\Main#index
[1] => GET
)
[home/] => Array
(
[0] => Dashboard\Main#index
[1] => GET
)
)
When at the moment, it's showing:
Array
(
[0] => Array
(
[services/content-writing] => Array
(
[0] => Dashboard\Services#contentwriting
[1] => GET
)
)
[1] => Array
(
[services/pbn-links] => Array
(
[0] => Dashboard\Services#pbnlinks
[1] => GET
)
)
)
The code I'm currently using inside my foreach loop is:
$realArray = array();
// Services exist
if($services)
{
// Sort them into our array
foreach ($services as $service) {
$servicePageName = $service->page_name;
$serviceName = str_replace(' ', '', strtolower($service->name));
$realArrayNew = array(
"services/$servicePageName" => ["Dashboard\Services#$serviceName", 'GET']
);
array_push($realArray, $realArrayNew);
//'home' => ['Dashboard\Main#index', 'GET'],
}
}
return $realArray;
The servicePageName variable must be the key field on the realArray to get the results you want.
I'm presuming you input object array looks something like this:
[
(int) 0 => object(stdClass) {
name => 'contentwriting'
page_name => 'content-writing'
},
(int) 1 => object(stdClass) {
name => 'pbnlinks'
page_name => 'pbn-links'
}
]
If we do this:
$realArray = [];
if ($services) {
foreach ($services as $service) {
$servicePageName = $service->page_name;
$serviceName = str_replace(' ', '', strtolower($service->name));
$realArray["services/$servicePageName"] = [
0 => "Dashboard\Services#$serviceName",
1 => "GET"
];
}
}
This is what we get on realArray:
[
'services/content-writing' => [
(int) 0 => 'Dashboard\Services#contentwriting',
(int) 1 => 'GET'
],
'services/pbn-links' => [
(int) 0 => 'Dashboard\Services#pbnlinks',
(int) 1 => 'GET'
]
]
This portion of the code inserts a new subarray to your main array:
$realArrayNew = array(
"services/$servicePageName" => ["Dashboard\Services#$serviceName", 'GET']
);
array_push($realArray, $realArrayNew);
Replace it all with:
$realArray["services/$servicePageName"] = ["Dashboard\Services#$serviceName", 'GET'];
That way your top level will have service names as keys.
I am getting response from SMS API call like below
stdClass Object (
[balance] => 3
[batch_id] => 289728321
[cost] => 2
[num_messages] => 2
[message] => stdClass Object (
[num_parts] => 1
[sender] => TXTLCL
[content] => This is test message from abc
)
[receipt_url] =>
[custom] =>
[messages] => Array (
[0] => stdClass Object (
[id] => 1172603746 [recipient] => 919796736174 )
[1] => stdClass Object (
[id] => 1172603747 [recipient] => 919858566712)
)
[status] => success
)
The code which I am trying to tweak is like below
if(count($this->capturedResponse) > 0)
{
foreach($this->capturedResponse as $response)
{
$balance = $response[0];
$batch_id = $response[1];
...
}
}
I am not able to separate the stdClass Object fields separately and put them in their corresponding variables.
Please Help !!!
Please try like this
$balance = $response->balance;
$batch_id = $response->batch_id;
The easiest way is to JSON-encode your object and then decode it back to an array:
$capturedResponse = (object) (array(
'balance' => 1,
'batch_id' => 289728321,
'cost' => 2,
'num_messages' => 2,
'message' => (object) (array(
'num_parts' => 1
))
));
$array = json_decode(json_encode($capturedResponse), True);
echo $array['balance'];
You need to use -> to get element from object, so use like this
$balance = $response->balance;
$batch_id = $response->batch_id;
Instead
$balance = $response[0];
$batch_id = $response[1];
...
To get content of message
$message = $response->message->content
Try yourself for messages by loop let us know if any problem
Update
$messagesObj = $response->messages;
$messagesArr = array();
foreach($messagesObj as $key=>$value){
$messagesArr[] = $value->recipient;
}
$messages = implode(",",$messagesArr);
You will get 919796736174, 919858566712 in $messages
regarding in query from the model, i got already the values and store it from a variable, now i want it to be stored from a data array for further use, how can i do this, i am in controller from codeigniter.
Here is my controller full code:
public function move_data($queue_id) {
$data = array();
$user = array('user_id' => $this->session->userdata['logged_in']['user_id']);
$getqueuedata = $this->Clinic_model->queue_data($queue_id,$user);
//echo json_encode($getqueuedata);
$data = array (
'queue_id' => $getqueuedata['queue_id'],
'user_id' => $getqueuedata['user_id'],
'clinic_id' => $getqueuedata['clinic_id'],
'order_num' => $getqueuedata['order_num'],
'patient_id' => $getqueuedata['patient_id'],
);
}
when i //echo json_encode($getqueuedata); uncomment this line, and comment the array storing, i will have this:
[{"user_id":"102","clinic_id":"2","order_num":"1","patient_id":"7","status":"2","time_sched":null,"queue_id":"1"}]
in my full code, i got error, i dont know how to store the values of my query from array.
function 'queue_data` return result like this :
//$getqueuedata = json_decode($json,true);
Array ( [0] => Array ( [user_id] => 102 [clinic_id] => 2 [order_num] => 1 [patient_id] => 7 [status] => 2 [time_sched] => [queue_id] => 1 ) )
So you can store data as this way:
$data = array (
'queue_id' => $getqueuedata[0]['queue_id'],
'user_id' => $getqueuedata[0]['user_id'],
'clinic_id' => $getqueuedata[0]['clinic_id'],
'order_num' => $getqueuedata[0]['order_num'],
'patient_id' => $getqueuedata[0]['patient_id'],
);
print_r($getqueuedata);
If your function return array object:
$data = array (
'queue_id' => $getqueuedata[0]->queue_id,
'user_id' => $getqueuedata[0]->user_id,
'clinic_id' => $getqueuedata[0]->clinic_id,
'order_num' => $getqueuedata[0]->order_num,
'patient_id' => $getqueuedata[0]->patient_id,
);
I need your help for this case.
I have an array in PHP.
How can I apply this array:
$visits = $ga->query($params);
Witch gave me something like this:
Array
(
[http_code] => 200
[kind] => analytics#gaData
[rows] => Array
(
[0] => Array
(
[0] => 20141223
[1] => 26
)
[1] => Array
(
[0] => 20141224
[1] => 15
)
...
In this code :
<? function getVisits() {
$morris = new MorrisLineCharts('getVisits');
$morris->xkey = array('date');
$morris->ykeys = array('value');
$morris->labels = array('Money');
$morris->data = array(
array('date' => '20141223', 'value' => 26),
array('date' => '20141224', 'value' => 15),
);
echo $morris->toJavascript();
}
getVisits();
?>
Thanks a lot.
You could loop over the data returned by Google Analytics, to construct an array suitable for Morris.
<? function getVisits( $ga_rows = array() ) {
foreach( $ga_rows as &$_row ) {
$_row = array('date' => $_row [0], 'value' => $_row [1]);
}
$morris = new MorrisLineCharts('getVisits');
$morris->xkey = array('date');
$morris->ykeys = array('value');
$morris->labels = array('Money');
$morris->data = $ga_rows;
echo $morris->toJavascript();
}
// the relevant data from the array you retreived from Google Analytics
getVisits( $google_analytics_data['rows'] );
?>
I have this array in php returned from db
Array
(
[inv_templates] => Array
(
[0] => Array
(
[inven_subgroup_template_id] => 1
[inven_group] => Wires
[inven_subgroup] => CopperWires
[inven_template_id] => 1
[inven_template_name] => CopperWires6G
[constrained] => 0
[value_constraints] =>
[accept_range] => 2 - 16
[information] => Measured Manual
)
[1] => Array
(
[inven_subgroup_template_id] => 1
[inven_group] => Wires
[inven_subgroup] => CopperWires
[inven_template_id] => 2
[inven_template_name] => CopperWires2G
[constrained] => 0
[value_constraints] =>
[accept_range] => 1 - 7
[information] => Measured by Automated Calipers
)
)
)
I need to output this kind of multidimensional stuff
Array
(
[Wires] => Array
(
[inv_group_name] => Wires
[inv_subgroups] => Array
(
[CopperWires] => Array
(
[inv_subgroup_id] => 1
[inv_subgroup_name] => CopperWires
[inv_templates] => Array
(
[CopperWires6G] => Array
(
[inv_name] => CopperWires6G
[inv_id] => 1
)
[CopperWires2G] => Array
(
[inv_name] => CopperWires2G
[inv_id] => 2
)
)
)
)
)
)
I currently do this stuff
foreach ($data['inv_templates'] as $key => $value) {
$processeddata[$value['inven_group']]['inv_group_name'] = $value['inven_group'];
$processeddata[$value['inven_group']]['inv_subgroups'][$value['inven_subgroup']]['inv_subgroup_id'] = $value['inven_subgroup_template_id'];
$processeddata[$value['inven_group']]['inv_subgroups'][$value['inven_subgroup']]['inv_subgroup_name'] = $value['inven_subgroup'];
$processeddata[$value['inven_group']]['inv_subgroups'][$value['inven_subgroup']]['inv_templates'][$value['inven_template_name']]['inv_name'] = $value['inven_template_name'];
$processeddata[$value['inven_group']]['inv_subgroups'][$value['inven_subgroup']]['inv_templates'][$value['inven_template_name']]['inv_id'] = $value['inven_template_id'];
}
return $processeddata;
EDIT : A var_export
array (
'inv_templates' =>
array (
0 =>
array (
'inven_subgroup_template_id' => '1',
'inven_group' => 'Wires',
'inven_subgroup' => 'CopperWires',
'inven_template_id' => '1',
'inven_template_name' => 'CopperWires6G',
'constrained' => '0',
'value_constraints' => '',
'accept_range' => '2 - 16',
'information' => 'Measured Manual',
),
1 =>
array (
'inven_subgroup_template_id' => '1',
'inven_group' => 'Wires',
'inven_subgroup' => 'CopperWires',
'inven_template_id' => '2',
'inven_template_name' => 'CopperWires6G',
'constrained' => '0',
'value_constraints' => '',
'accept_range' => '1 - 7',
'information' => 'Measured by Automated Calipers',
),
),
)
The foreach is almost unreadable. There must be a simpler way
$processeddata = array();
foreach($data['inv_templates'] as $key => $value) {
$group = $value['inven_group'];
$processeddata[$group]['inv_group_name'] = $group;
$subgroup = &$processeddata[$group]['inv_subgroups'][$value['inven_subgroup']];
$subgroup['inv_subgroup_id'] = $value['inven_subgroup_template_id'];
$subgroup['inv_subgroup_name'] = $value['inven_subgroup'];
$template = $value['inven_template_name'];
$subgroup['inv_templates'][$template]['inv_name'] = $template;
$subgroup['inv_templates'][$template]['inv_id'] = $value['inven_template_id'];
}
return $processeddata;
Untested code. This structures the array in a multidimensional way, and then uses array_merge_recursive to merge them with the already processed data.
if (!isset($processeddata[$value['inven_group']]))
$processeddata[$value['inven_group']] = array();
$processeddata[$value['inven_group']] = array_merge_recursive(
$processeddata[$value['inven_group']],
array(
'inv_group_name' => $value['inven_group'],
'inv_subgroups' => array(
$value['inven_subgroup'] => array(
'inv_subgroup_id' => $value['inven_subgroup_template_id'],
'inv_subgroup_name' => $value['inven_subgroup'],
'inv_templates' => array(
$value['inven_template_name'] => array(
'inv_name' => $value['inven_template_name'],
'inv_id' => $value['inven_template_id'],
),
),
),
),
)
);
I find this format usually works for me. You could do it more efficient, I've just never cared :D
I started traversing at $yourArray['inv_templates'] though.
function groupToStructure(array $rows, array $keys) {
$tree = array();
$keys = array_reverse($keys);
foreach ($rows as $row) {
$subTree = array($row);
foreach ($keys as $key) {
$subTree = array($row[$key] => $subTree);
}
$tree = array_merge_recursive($tree, $subTree);
}
return $tree;
}
print_r(groupToStructure($rows, array('inven_group', 'inven_subgroup', 'inven_template_name')));