unable to add key value pairs to complex object in php - php

I'm trying to create the follwing object in PHP:
$obj= {abc#gmail.com:[usr:130,fname:'Bob',lname:'thekid',news:0,wres:1,SWAGLeaders:0]}
ultimately $obj will have a number of email addresses each with its own array.
Here's what I have so far:
$obj = new stdClass();
$obj->{$user[0]['email']}=[];
where $user[0]['email] contains the email address.
my problem is I don't know how to add the elements to the array

You are on the right path if you really need an object.
$user[0]['email'] = 'test';
$obj = new stdClass();
$obj->{$user[0]['email']} = ['usr' => 130, 'fname' => 'Bob', 'lname' => 'thekid', 'news' => 0, 'wres' => 1, 'SWAGLeaders' => 0];
echo json_encode($obj);
Here's the output.
http://sandbox.onlinephpfunctions.com/code/035266a29425193251b74f0757bdd0a3580a31bf
But, I personally don't see a need for an object, I'd go with an array with a bit simpler syntax.
$user[0]['email'] = 'test';
$obj[$user[0]['email']] = ['usr' => 130, 'fname' => 'Bob', 'lname' => 'thekid', 'news' => 0, 'wres' => 1, 'SWAGLeaders' => 0];
echo json_encode($obj);
http://sandbox.onlinephpfunctions.com/code/13c1b5308907588afc8721c1354f113c641f8788

The same way you assigned the array to the object in the first place.
$user[0]['email'] = "abc#gmail.com";
$obj = new stdClass;
$obj->{$user[0]['email']} = [];
$obj->{$user[0]['email']}[] = "Element 1";
$obj->{$user[0]['email']}[] = "Element 2";
$obj->{$user[0]['email']}[] = "Element 3";
var_dump($obj);
object(stdClass)#1 (1) {
["abc#gmail.com"]=>
array(3) {
[0]=>
string(9) "Element 1"
[1]=>
string(9) "Element 2"
[2]=>
string(9) "Element 3"
}
}

Related

Is there way to get value of CDATA and convert in json or array format in php?

Here is what it looks like after getting value from CDATA via simplexmlelement
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}"
I tried looking into solutions in google but i am not able to find one which would convert this set of strings to array.
I want this data to convert into array something like this
["customertype"] = ["New"]
["Telephone"] = ["09832354544"]
so and so forth or something similar as how array looks like.
Thanks in advance
Given your data string format, you may do as follows:
First of all, remove the brackets { }
Then explode the string using the , delimiter.
Now, you have array of strings containing for example customertype=New.
Next is the tricky part, the result string looks like a query, so we're gonna use
parse_str() to make an associative array:
The result will be something similar to this:
array:9 [▼
0 => array:1 [▼
"customertype" => "New"
]
1 => array:1 [▼
"Telephone" => "09832354544"
]
2 => array:1 [▼
"CITY" => "Henfield"
]
And here's the code:
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
$rippedData = str_replace(["{", "}"],"", $data);
$singleData= explode(",", $rippedData);
$finalArray = [];
foreach($singleData as $string){
parse_str($string, $output);
$finalArray[] = $output;
}
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
$stripped = str_replace(['{','}'], '', $data);
$explode = explode(', ', $stripped);
$output = [];
foreach ($explode as $value) {
$inner_explode = explode('=', $value);
$output[$inner_explode[0]] = $inner_explode[1];
}
var_dump($output);
Results in
array(9) {
["customertype"]=>
string(3) "New"
["Telephone"]=>
string(11) "09832354544"
["CITY"]=>
string(8) "Henfield"
["LASTNAME"]=>
string(1) "C"
["TicketNo"]=>
string(6) "123456"
["FIRSTNAME"]=>
string(4) "Alex"
["Id"]=>
string(8) "10001273"
["testfield"]=>
string(6) "123456"
["COMPANY"]=>
string(5) "Camp1"
}
This should work, though there's probably a better/cleaner way to code this.
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
// Replace squiggles
$replace_this = array("{","}");
$replace_data = str_replace($replace_this,"",$data);
// Explode and create array
$data_array = explode(',',$replace_data);
// Loop through the data_array
foreach($data_array as $value) {
// Explode the value on the equal sign
$explode_again = explode('=', $value);
// Create new array with correct indexes and values
$CDTA[trim($explode_again[0])] = $explode_again[1];
}
echo '<pre>' . var_export($CDTA, true) . '</pre>';
Result:
array (
'customertype' => 'New',
'Telephone' => '09832354544',
'CITY' => 'Henfield',
'LASTNAME' => 'C',
'TicketNo' => '123456',
'FIRSTNAME' => 'Alex',
'Id' => '10001273',
'testfield' => '123456',
'COMPANY' => 'Camp1',
)

Not able to access data inside a PHP array of object

I´m trying to access data inside a object create after a response(from a dafiti server) with no succsess.
Bellow my code:
***$response = Endpoints::order()->getOrder($orderId)->call($client);
$o = $response->getBody();
echo "<pre>";
var_dump($o);
echo "</pre>";
foreach($o as $value => $obj){
$orderId = $obj->Order->OrderID;// tried this way(not working)
$CustomerFirstName = $obj['Order']['CustomerFirstName'];// tried this way(not working)
}******
Bellow the var_dump:
array(1) {
["Orders"]=>
array(1) {
["Order"]=>
array(23) {
["OrderId"]=>
string(7) "8266761"
["CustomerFirstName"]=>
string(6) "sheila"
["CustomerLastName"]=>
string(14) "rocha domingos"
["OrderNumber"]=>
string(10) "4510948375"
["PaymentMethod"]=>
string(22) "braspag_cc_master_card"
["Currency"]=>
string(3) "BRL"
... to be continue.
How can I access the values inside this array?
Your array contains an array of orders inside of the 'Orders' field of the $o array. So you need to iterate over $o['Orders']. Then you'll be able to access your order details.
<?php
$o = [
'Orders' => [
'Order' => [
'OrderId' => '8266761',
'CustomerFirstName' => 'sheila',
'CustomerLastName' => 'rocha domingos',
'OrderNumber' => '4510948375',
'PaymentMethod' => 'braspag_cc_master_card',
'Currency' => 'BRL'
]
]
];
foreach ($o['Orders'] as $order) {
$orderId = $order['OrderId'];
$CustomerFirstName = $order['CustomerFirstName'];
var_dump($orderId); // 8266761
var_dump($CustomerFirstName); // sheila
}

Check if value is in array PHP (easy?)

I think I have a very easy question, but I am stuck anyway. I want to check if the value is in an array, and if it is, i want to change the variable value.
$admin_is_menu = "about";
$test = array();
$test = [
["Name" => "About","alias" => "about"],
["Name" => "Test", "alias" => "test"],
];
if(in_array($admin_is_menu, $test)){
$admin_is_menu = "true";
}
echo $admin_is_menu;
In the code above, it should output the echo "true", since "about" is in the array. But is unfortunally does not work.
What am I doing wrong?
Try array_column to get all array value.
$admin_is_menu = "about";
$test = array();
$test = [
["Name" => "About","alias" => "about"],
["Name" => "Test", "alias" => "test"],
];
if(in_array($admin_is_menu, array_column($test,'alias'))){
$admin_is_menu = "true";
}
echo $admin_is_menu;
DEMO
#cske pointed out in the comment how to do it. Here's a small explanation for that as well.
You should use array_column. In this case array_column($test, "alias") will return a new array:
array(2) {
[0]=>
string(5) "about"
[1]=>
string(4) "test"
}
Now, you check within it with in_array:
in_array($admin_is_menu, array_column($test,'alias'))
and this will return true

Reading PHP array using key value

I have an array that I'm creating inside my PHP script, the var_dump function gives me this value :var_dump($arrayOfValues);
array(3) {
[0]=> array(2) {
[0]=> string(12) "BusinessName"
[1]=> string(13) "ITCompany"
}
[1]=> array(2) {
[0]=> string(7) "Address"
[1]=> string(58) "29 xxxxxx,Canada"
}
[2]=> array(2) {
[0]=> string(20) "PrimaryBusinessPhone"
[1]=> string(14) "(444) 111-1111"
}
[3]=> array(2) {
[0]=> string(13) "BusinessEmail"
[1]=> string(24) "xx#example.com"
}
}
I would like to access to the value of the "BusinessName" using key and not index so if I put : echo $arrayOfValue[0][1]; it gives me the BusinessName that is ITCompany but if I put
: echo $arrayOfValue['BusinessName'][1]; it gives nothing so how can I fix that please?
The array is initialized $arrayOfValue = array(); and then populated dynamically inside a for loop like that
$arrayOfValue[] = array($Label, $Value);
your array has this kind of data
$arrayOfPostsValue[] = array("BusinessName","ITCompany");
$arrayOfPostsValue[] = array("Address","29 xxxxxx,Canada");
$arrayOfPostsValue[] = array("PrimaryBusinessPhone","(444) 111-1111");
$arrayOfPostsValue[] = array("BusinessEmail","xx#example.com");
there is no array key in data So, you have to recreate your desire array
$newArrayOfPostsValue = array();
foreach ( $arrayOfPostsValue as $value ){
$newArrayOfPostsValue[$value[0]] = $value[1];
}
print_r($newArrayOfPostsValue);
and here is output
Array
(
[BusinessName] => ITCompany
[Address] => 29 xxxxxx,Canada
[PrimaryBusinessPhone] => (444) 111-1111
[BusinessEmail] => xx#example.com
)
As mentioned in the comment, change the structure of the array, it will be much easier to handle
$my_array = array(
array('Business Name' => 'It Company'),
array('Address' => 'My address')
);
Looking at the content of your array, I will restructure it as
$my_improved_array = array(
'BusinessName' => 'It Company',
'Address' => 'My Address',
);
This is how you can access,
echo $my_array[0]['BusinessName'] //prints 'It Company'
echo $my_array[1]['Address'] //prints 'My Address'
echo $my_improved_array['BusinessName'] // prints 'It Company'
Try like this and save array as key value pairs and then access the key:
foreach($arrayOfValues as $a)
$arr[$a[0]] = $a[1];
echo $arr['BusinessName'];
While creating that array build it with index as BusinessName
array (
0 => array(
'BusinessName'=> "ITCompany"
)
1 => array(1) (
'Address'=> "29 xxxxxx,Canada"
)
)
etc..
PHP Array example
$array = array();
$array['BusinessName'] = 'ITCompany';
$array['Address'] = '29 xxxxxx,Canada';
And so on... Now you can echo values with
echo $array['BusinessName'];
Also this works
$array = array('BusinessName' => 'ITCompany', 'Address' => '29 xxxxxx,Canada');
First of all, how are you building this array ? Maybe you can directly make a workable array.
Anyway, you can do something like this :
$oldArray = Array(
Array("BusinessName", "ITCompany"),
Array("Address", "29 xxxxxx,Canada"),
Array("PrimaryBusinessPhone", "(444) 111-1111"),
Array("BusinessEmail", "xx#example.com")
);
$newArray = Array();
foreach($oldArray as value) {
$newValue[$value[0]] = $value[1];
}
/* Now, it's equal to
$newArray = Array(
"BusinessName" => "ITCompany",
"Address" => "29 xxxxxx,Canada",
"PrimaryBusinessPhone" => "(444) 111-1111",
"BusinessEmail" => "xx#example.com"
);
*/

Array of PHP Objects

So I have been searching for a while and cannot find the answer to a simple question. Is it possible to have an array of objects in PHP? Such as:
$ar=array();
$ar[]=$Obj1
$ar[]=$obj2
For some reason I have not been able to find the answer anywhere. I assume it is possible but I just need to make sure.
The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.
-- Edit --
class Car
{
public $color;
public $type;
}
$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';
$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';
$cars = array($myCar, $yourCar);
foreach ($cars as $car) {
echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}
Yes.
$array[] = new stdClass;
$array[] = new stdClass;
print_r($array);
Results in:
Array
(
[0] => stdClass Object
(
)
[1] => stdClass Object
(
)
)
Yes, its possible to have array of objects in PHP.
class MyObject {
private $property;
public function __construct($property) {
$this->Property = $property;
}
}
$ListOfObjects[] = new myObject(1);
$ListOfObjects[] = new myObject(2);
$ListOfObjects[] = new myObject(3);
$ListOfObjects[] = new myObject(4);
print "<pre>";
print_r($ListOfObjects);
print "</pre>";
You can do something like this:
$posts = array(
(object) [
'title' => 'title 1',
'color' => 'green'
],
(object) [
'title' => 'title 2',
'color' => 'yellow'
],
(object) [
'title' => 'title 3',
'color' => 'red'
]
);
Result:
var_dump($posts);
array(3) {
[0]=>
object(stdClass)#1 (2) {
["title"]=>
string(7) "title 1"
["color"]=>
string(5) "green"
}
[1]=>
object(stdClass)#2 (2) {
["title"]=>
string(7) "title 2"
["color"]=>
string(6) "yellow"
}
[2]=>
object(stdClass)#3 (2) {
["title"]=>
string(7) "title 3"
["color"]=>
string(3) "red"
}
}
Arrays can hold pointers so when I want an array of objects I do that.
$a = array();
$o = new Whatever_Class();
$a[] = &$o;
print_r($a);
This will show that the object is referenced and accessible through the array.
Another intuitive solution could be:
class Post
{
public $title;
public $date;
}
$posts = array();
$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';
$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';
foreach ($posts as $post) {
echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}
Although all the answers given are correct, in fact they do not completely answer the question which was about using the [] construct and more generally filling the array with objects.
A more relevant answer can be found in
how to build arrays of objects in PHP without specifying an index number?
which clearly shows how to solve the problem.

Categories