Trying to make an array of objects in php - php

I try to iterate through an array by using this function:
public static function getDataForChartAlexaDailyRank($data)
{
$asd = [];
$new = [];
$site = [];
for ($x = 0; $x < sizeof($data->data); $x++) {
foreach ((array)#$data->data->{$x} as $value) {
array_push($site, intval($value->{"Response"}->{"TrafficHistoryResult"}->{"Alexa"}->{"TrafficHistory"}->{"Site"}));
}
foreach ((array)#$data->data->{$x} as $value) {
array_push($new, intval($value->{'Response'}->{'TrafficHistoryResult'}->{'Alexa'}->{'TrafficHistory'}->{'HistoricalData'}->{'Data'}->{'Rank'}));
}
$asd[] = ['name' => $site, 'data' => $new];
$new = [];
}
return json_encode($asd);
}
The array looks like this:
["data"]=>
object(stdClass)#229 (2) {
["mainUrl"]=>
object(stdClass)#235 (1) {
["Response"]=>
object(stdClass)#238 (2) {
["OperationRequest"]=>
object(stdClass)#237 (1) {
["RequestId"]=>
string(36) "1d7824a5-dc09-4efb-9f2a-b35055abc04d"
}
["TrafficHistoryResult"]=>
object(stdClass)#241 (1) {
["Alexa"]=>
object(stdClass)#242 (1) {
["TrafficHistory"]=>
object(stdClass)#243 (4) {
["Range"]=>
string(2) "31"
["Site"]=>
string(25) "https://app.klipfolio.com"
["Start"]=>
string(10) "2016-07-01"
["HistoricalData"]=>
object(stdClass)#244 (1) {
["Data"]=>
array(31) {
[0]=>
object(stdClass)#245 (4) {
["Date"]=>
string(10) "2016-07-01"
["PageViews"]=>
object(stdClass)#246 (2) {
["PerMillion"]=>
string(3) "2.5"
["PerUser"]=>
string(4) "5.50"
}
["Rank"]=>
string(5) "30467"
["Reach"]=>
object(stdClass)#247 (1) {
["PerMillion"]=>
string(2) "30"
}
}
}
}
}
}
}
}
}
["competitorUrl1"]=>
object(stdClass)#338 (1) {
["Response"]=>
object(stdClass)#339 (2) {
["OperationRequest"]=>
object(stdClass)#340 (1) {
["RequestId"]=>
string(36) "ac7ba0b9-c789-5f6a-f1c8-714587b494e9"
}
["TrafficHistoryResult"]=>
object(stdClass)#341 (1) {
["Alexa"]=>
object(stdClass)#342 (1) {
["TrafficHistory"]=>
object(stdClass)#343 (4) {
["Range"]=>
string(2) "31"
["Site"]=>
string(23) "http://onlinesupport.io"
["Start"]=>
string(10) "2016-07-01"
["HistoricalData"]=>
object(stdClass)#344 (0) {
["Data"]=>
array(31) {
[0]=>
object(stdClass)#245 (4) {
["Date"]=>
string(10) "2016-07-01"
["PageViews"]=>
object(stdClass)#246 (2) {
["PerMillion"]=>
string(3) "2.5"
["PerUser"]=>
string(4) "5.50"
}
["Rank"]=>
string(5) "30467"
["Reach"]=>
object(stdClass)#247 (1) {
["PerMillion"]=>
string(2) "30"
}
}
}
}
}
}
}
}
}
}
The array is stored in the variable $data (hence the $data-data to access the array) and I have to iterate through both objects (["mainUrl"] and ["competitorUrl1"] to get the ["Site"] and ["Rank"] and store them into the variable $asd. The function I have written tries to do this. I say tries because I don't know how to properly iterate thorugh objects with different names (["mainUrl"] and ["competitorUrl1"]). I am sorry if I did not explain it well enough but I am a noob in php, so if you have any questions please ask. Thank you very much for your time.

foreach ((array)#$data->data[$x]->{'Response'}->{'TrafficHistoryResult'}->{'Alexa'}->{'TrafficHistory'}->{'HistoricalData'}->{'Data'} as $value) {
Did you forget ->{'mainUrl'} there? So it would be something like follows:
public static function getDataForChartAlexaDailyRank($data)
{
$asd = [];
$new = [];
for ($x = 0; $x < sizeof($data->data); $x++) {
$site = $data->data[$x]->{'mainUrl'}->{'Response'}->{'TrafficHistoryResult'}->{'Alexa'}->{'TrafficHistory'}->{'Site'};
foreach ($data->data[$x]->{'mainUrl'}->{'Response'}->{'TrafficHistoryResult'}->{'Alexa'}->{'TrafficHistory'}->{'HistoricalData'}->{'Data'} as $value) {
array_push($new, intval($value->{'Rank'}));
}
$asd[] = ['name' => $site, 'data' => $new];
$new = [];
}
return json_encode($asd);
}

Related

Structure array into multi dimensional array

So I have the following variable $authenticated_users which returns:
array(2) {
[0]=>
array(5) {
["username"]=> string(16) "saint"
["user_id"]=> int(17841404774727369)
["access_token"]=> string(142) "IGQ3"
["access_token_expiration"]=> int(1650688769)
["last_updated"]=> int(1645537675)
}
[1]=>
array(5) {
["username"]=> string(9) "sem"
["user_id"]=> int(17841400835712753)
["access_token"]=> string(140) "IGQ"
["access_token_expiration"]=> int(1650683675)
["last_updated"]=> int(1645537891)
}
}
So I have the following method:
public static function get_config_and_users(): array
{
$config = [];
$config['client_id'] = '2882';
$config['client_secret'] = '521f4e';
if (!$authenticated_users = get_option('instagram')) {
return [];
}
foreach ($authenticated_users as $user) {
$config['authenticated_users'] = [
$config['username'] = $user['username']
];
}
echo '<pre>';
var_dump($config);
echo '</pre>';
die();
return $config;
}
When I echo $config I get the following results:
array(4) {
["client_id"]=> string(15) "28822"
["client_secret"]=> string(32) "521f4e8"
["username"]=> string(9) "sem"
["authenticated_users"]=> array(1) {
[0]=> string(9) "sem"
}
}
Here is what I'm attempting to do:
array(4) {
["client_id"]=> string(15) "2882"
["client_secret"]=> string(32) "521f4e5"
["authenticated_users"] => {
[0]=> array(1) {
['username']=> string(16) "saint"
....
}
[1]=>
array(1) {
['username']=> string(9) "sem"
....
}
}
}
Does anyone know what I can do to improve my code?
you need to change your logic
public static function get_config_and_users(): array
{
$config = [];
$config['client_id'] = '2882';
$config['client_secret'] = '521f4e';
if (!$authenticated_users = get_option('instagram')) {
return [];
}
foreach ($authenticated_users as $user) {
$config['authenticated_users'][] = [
'username' => $user['username']
];
}
return $config;
}

How to group a multidimensional array by multiple subarray values?

I checked this question and answers:
How to group a multidimensional array by a particular subarray value?
He wanted to group results by 'level'. But how would you do it to group it by 'level' first and then by 'type'?
Its pretty straight forward. Loop through $items array. Get each item's level and type and if they are not set yet, initialize them with an empty array. Then just push the "cust" value into the array.
I have given the code below.
I am assuming "$items" is an array which contains the input.
$g = [];
foreach($items as $k => $v) {
$l = $v["level"];
$t = $v["type"];
$c = $v["cust"];
if(!isset($g[$l])) {
$g[$l] = [];
}
if(!isset($g[$l][$t])) {
$g[$l][$t] = [];
}
$g[$l][$t][] = [
"cust" => $c
];
}
var_dump($g);
The output of this code would be like below:
array(3) {
[1]=>
array(1) {
["standard"]=>
array(2) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT8900"
}
[1]=>
array(1) {
["cust"]=>
string(6) "XT8944"
}
}
}
[3]=>
array(1) {
["premier"]=>
array(2) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT8922"
}
[1]=>
array(1) {
["cust"]=>
string(6) "XT8816"
}
}
}
[7]=>
array(1) {
["standard"]=>
array(1) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT7434"
}
}
}
}
[P.S.]: You can also use sort to solve this problem easily. That's another way of solving this problem.

Assigning specific element of multidimensional array in url in php

My goal is to get specific element/value from a multidimensional array and assign them in a URL in loop. I have already tried and was able to get elements in the array but this displays all elements. I only want to get specific, like nid and field_x values.
This is my link structure: http://localhost:8080/$nid/$field_x
Expected result:
http://localhost:8080/123/one
http://localhost:8080/789/three
This is my sample var_dump result
array(1) {
[0]=>
array(38) {
["nid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(123)
}
}
["vid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(456)
}
}
["field_x"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(6) "One"
}
}
["field_y"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(2) "Two"
}
}
}
[1]=>
array(38) {
["nid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(789)
}
}
["vid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(321)
}
}
["field_x"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(6) "Three"
}
}
["field_y"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(2) "Four"
}
}
}
}
You can use a foreach() and get the data using $values['nid'][0]['value'] or $values['field_x'][0]['target_id']:
foreach ($result as $values) {
$nid = $values['nid'][0]['value'];
$field_x = $values['field_x'][0]['target_id'];
echo "http://localhost:8080/$nid/$field_x" ;
}
Will outputs:
http://localhost:8080/123/One
http://localhost:8080/789/Three
You probably want to do something else than an echo, so you can create a new array:
$urls = [];
foreach ($result as $values) {
$nid = $values['nid'][0]['value'];
$field_x = $values['field_x'][0]['target_id'];
$urls[] = "http://localhost:8080/$nid/$field_x" ;
}
print_r($urls);

Get path to parent node of (parent/child) array

Given the following array:
array(..) {
[1111]=>
&array(3) {
["category_id"]=>
int(1111)
["parent_id"]=>
int(0)
["children"]=>
array(2) {
[2222]=>
&array(3) {
["category_id"]=>
int(2222)
["parent_id"]=>
int(1111)
["children"]=>
array(2) {
[5555]=>
&array(1) {
["category_id"]=>
int(5555)
["parent_id"]=>
int(2222)
}
}
[3333]=>
&array(2) {
["category_id"]=>
int(3333)
["parent_id"]=>
int(1111)
}
}
Assuming that the array depth is unknown, How can I determine the path to the parent node?
For example, for category_id = 5555 I should get the following result: 0, 1111,2222. For category_id = 3333 it would be 0,1111
One approach:
function findParent($node, $array, &$parents) {
if (array_key_exists($node, $array)) {
$parents[] = $array[$node]['parent_id'];
}
else {
foreach ($array as $item) {
if (array_key_exists('children', $item)) {
$parents[] = $item['parent_id'];
findParent($node, $item['children'], $parents);
}
}
}
}
findParent(5555, $A, $parents);

Recursive JSON transformation

Suppose I have a JSON string:
$json = '{"lemon":"test",
"orange":["toto", "tata", "tete"],
"zob":[{"id":"0"}, {"id":"1"}]}';
I'd like to cycle through that encoded object to modify every string in it, so I have a recursive function:
function doObject($__obj){
$__obj = cycleObject($__obj);
return $__obj;
}
function cycleObject($__obj){
$type = gettype($__obj);
foreach($__obj as $var => &$val){
switch(gettype($val)){
case 'object':
cycleObject($val);
break;
case 'array':
cycleObject($val);
break;
case 'string':
if($type == 'object'){
$__obj->$var = $val.'-ok';
}else{
if($type == 'array'){
$__obj[$var] = $val.'-ok';
}
}
break;
}
}
return $__obj;
}
And I call the function:
$obj = doObject(json_decode($json));
var_dump($obj);
Which gives :
object(stdClass)#1 (3) {
["lemon"]=> string(7) "test-ok"
["orange"]=> array(3) {
[0]=> string(4) "toto"
[1]=> string(4) "tata"
[2]=> string(4) "tete" }
["zob"]=> array(2) {
[0]=> object(stdClass)#2 (1) {
["id"]=> string(4) "0-ok" }
[1]=> object(stdClass)#3 (1) {
["id"]=> string(4) "1-ok" }
}
}
Now my problem is, for some reason, I am unable to modify directly inside an array composed by string, or should I say, the modified string inside an array (and not inside an object inside an array) because the array loses its reference. How do I fix that so in orange I instead obtain:
[0]=> string(7) "toto-ok"
[1]=> string(7) "tata-ok"
[2]=> string(7) "tete-ok"
Your array of strings isn't being scrutinized correctly by your function. Basically, in each array you need a second check to see if you are dealing with another array/object or a string, otherwise regular arrays of strings are being bypassed....oddly enough. The following should work for you:
$json = '{"lemon":"test",
"orange":["toto", "tata", "tete"],
"zob":[{"id":"0"}, {"id":"1"}]}';
function doObject($__obj){
$__obj = cycleObject($__obj);
return $__obj;
}
function cycleObject($__obj){
foreach($__obj as $key => &$val){
if(is_object($val)) {
cycleObject($val);
}
if(is_array($val)) {
foreach($val as &$v) {
if(is_object($v) || is_array($v)) {
cycleObject($v);
} else {
$v .= '-ok';
}
}
}
if(is_string($val)) {
$val .= '-ok';
}
}
return $__obj;
}
$obj = doObject(json_decode($json));
var_dump($obj);
This produced the results you were looking for in my local environment.
object(stdClass)#1 (3) {
["lemon"]=>
string(7) "test-ok"
["orange"]=>
array(3) {
[0]=>
string(7) "toto-ok"
[1]=>
string(7) "tata-ok"
[2]=>
string(7) "tete-ok"
}
["zob"]=>
array(2) {
[0]=>
object(stdClass)#2 (1) {
["id"]=>
string(4) "0-ok"
}
[1]=>
object(stdClass)#3 (1) {
["id"]=>
string(4) "1-ok"
}
}
}

Categories