Structure array into multi dimensional array - php

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;
}

Related

Optimizing PHP code with two foreach loops

I have an array that consists of the keys:
$countries = ['EU', 'UK', 'Asia'];
Another array that consists of further elements based on those keys:
$countries_array=['UK'=>['London', 'Birmingham', 'Manchester'], 'EU'=> ['Germany','Netherlands'] , 'Asia'=> ['Pakistan','Bangladesh','China']];
$mid_countries[];
I want to pass through all the elements, check if they are empty or not and then further create another array. I have written a code and it works fine. But it has foreach loops. Is there any way that I could optimize this code?
foreach ($countries as $each_country) {
if (!empty($countries_array["$each_country"][0])) {
foreach ($countries_array["$each_country"] as $value) {
$mid_countries[] = array("wildcard" => array("$each_country" => $value. "*"));
}
}
}
Expected result:
array(8) {
[0]=> array(1) { ["wildcard"]=> array(1) { ["EU"]=> string(8) "Germany*" } } [1]=> array(1) { ["wildcard"]=> array(1) { ["EU"]=> string(12) "Netherlands*"}}
[2]=> array(1) { ["wildcard"]=> array(1) { ["UK"]=> string(7) "London*" } } [3]=> array(1) { ["wildcard"]=> array(1) { ["UK"]=> string(11) "Birmingham*" } } [4]=> array(1) { ["wildcard"]=> array(1) { ["UK"]=> string(11) "Manchester*" } } [5]=> array(1) { ["wildcard"]=> array(1) { ["Asia"]=> string(9) "Pakistan*" } } [6]=> array(1) { ["wildcard"]=> array(1) { ["Asia"]=> string(11) "Bangladesh*"}}
[7]=> array(1) { ["wildcard"]=> array(1) { ["Asia"]=> string(6) "China*" } } }
I think you expected this (Code updated use its working in single loop)
foreach ($countries_array as $key=>$value) {
$tmp=implode('*#'.$key.'#',$value);
$tmp='#'.$key.'#'.$tmp."*";
$tmp=str_replace('#'.$key.'#',"\"}},{\"wildcard\":{\"".$key."\":\"",$tmp);
$result=$result.substr($tmp,3)."\"}}";
}
$result="[".ltrim($result,"\"}},")."]";
$result=json_decode($result,true);
print_r($result);

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);

Unable to iterate an array in a PHP foreach loop

My request PHP file elaborates some Ajax POST data:
POST data
data[0][id]:359
data[0][position]:1
data[1][id]:321
data[1][position]:2
data[2][id]:354
data[2][position]:3
Request.php
if(isset($_POST['data'])) {
if(isset($_SESSION['username']) && isset($_SESSION['password'])) {
$verify = $loggedIn->verify();
if($verify['username']) {
$Profile = new Profile();
$Profile->db = $db;
//Call my function
$messages = $Profile->setOrder($_POST['data']);
}
}
}
Profile.php
function setOrder($post) {
var_dump($post);
foreach($post as $item)
{
return "Area ID ".$item["id"]." and person located ".$item["position"]."<br />";
}
}
My function returns nothing and the dump of $post is as below
array(3) {
[0]=>
array(2) {
["id"]=>
string(3) "359"
["position"]=>
string(1) "1"
}
[1]=>
array(2) {
["id"]=>
string(3) "321"
["position"]=>
string(1) "2"
}
[2]=>
array(2) {
["id"]=>
string(3) "354"
["position"]=>
string(1) "3"
}
}
Inside my function I can dump correctly something like var_dump($post[0]["id"]); so why my foreach loop is empty?
It is because you are using return inside loop. It will terminate the loop after first iteration. You need to do something like this.
$return = null;
foreach($data as $item)
{
$return .= "Area ID ".$item["id"]." and person located ".$item["position"]."<br />";
}
return $return;

Trying to make an array of objects in 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);
}

Add Array Column to Multidimensional Array Using array_merge in foreach Loop

I'm trying to add another column of data to each row in a foreach loop. It's purpose is to remember the element of data importeded from XML processed to an multidimensional array. It's stuck as a scalar though the var_dumps looks fine.
<?php
$KEY = 0;
foreach ($eventsArray as $keyMe){
$thisKey['KEY'][0] = strval($KEY);
$keyedArray = array_merge($keyMe, $thisKey);
$KEY++;
}
// Prep for multisort
foreach ($keyedArray as $key => $value){
$date[$key] = $value['DATE'];
$title[$key] = $value['TITLE'];
$link[$key] = $value['LINK'];
$slide[$key] = $value['SLIDE'];
$location[$key] = $value['LOCATION'];
$time[$key]= $value['TIME'];
$KEY[$key] = $value['KEY']; // Warning: Cannot use a scalar value as an array
}
/* var_dump(
array(7) {
["DATE"]=> array(1) { [0]=> string(10) "2012-12-18" }
["TITLE"]=> array(1) { [0]=> string(20) "Event Title" }
["LINK"]=> array(1) { [0]=> string(38) "aLinkLocation.htm" }
["SLIDE"]=> array(1) { [0]=> string(2) "16" }
["LOCATION"]=> array(1) { [0]=> string(8) "Location of Event" }
["TIME"]=> array(1) { [0]=> string(3) "8am" }
["KEY"]=> array(1) { [0]=> string(2) "23" }
}
*/

Categories