Convert array of objects with keys to keyed array - php

I have an array of objects that are defined as {'preference name',value}. For example
$preferences[] = {'abc',123};
$preferences[] = {'def',456};
I'd like to access them like this:
$pref = $preferences['abc'];
Of course, I know I could assign them as a keyed array to begin with, however I'm getting the values via JSON, and json_decode always creates an array of objects. Some example JSON that leads us to the situation above would be:
{'abc':123,'def':456}
Obviously it's trivial to covert these using a loop, but I wondered if there was a better one-liner that might do the job?

If you decode the JSON into associative arrays AND all properties are unique, then just merge the sub arrays:
$preferences = json_decode($json, true);
$preferences = call_user_func_array('array_merge', $preferences);

Seems ugly, but hey, it works.
<?php
$a = ['abc'=>123,'def'=>456];
$obj = json_decode(json_encode($a));
var_dump($obj->abc); //123
$arr = (array)$obj;
var_dump($arr["abc"]); //123

Related

How to convert an object properties into an array in php

Those data in $data variable. When I'm using dd($data); I got this:
CurlHandle {#1918 ▼
+url: "https://example.com"
+content_type: "application/json; charset=UTF-8"
+http_code: 200
+header_size: 887
+namelookup_time_us: 139522
+pretransfer_time_us: 326662
+redirect_time_us: 0
+starttransfer_time_us: 668686
+total_time_us: 668752
}
I want to convert this data to an array.
I'm using this: $arr = json_decode($data,true);
But, this is not working. Now, how can I convert this?
You can use below solution
$yourArray = json_decode(json_encode($yourObject), true);
and this convert object to an array for more info
Objects are, in PHP, maybe iterable. Notice, you may iterate through an object's public fields only via the foreach loop. So the following works:
$array = [];
foreach ($object as $property) {
$array[] = $property; // Stores public field only
}
var_dump($array);
Simply to get an array of object properties, you may use the get_object_vars() function.
var_dump(get_object_vars($object));
You may cast an object to be an array as #MoussabKbeisy said. And this would be the easiest way:
$array = (array) $object;
Here is another way is using ArrayIterator:
$iterator = new ArrayIterator($object);
var_dump(iterator_to_array($iterator));
while this is a PHP Object so you can deal with it by 2 ways:
1- if you want to get on of it's parameters, you can simply use
$yourObject->parameter;
2- if you need to use convert and use it as array, then there is different ways to convert an object to an array in PHP
//1
$array = (array) $yourObject;
//2
$array = json_decode(json_encode($yourObject), true);
Also see this in-depth blog post:
Fast PHP Object to Array conversion

Converting to json correct way using php?

I need an o/p like this ["12","13"] when I do the following json operation
I have a 2 varaiables and getting these values as post data
$a = $_POST['cas'];
$b = $_POST['casty'];
$final1 = json_encode($a);
$final2= json_encode($b);
$final_value = '['.$final1.','.$final2.']';
I am getting output as ["12","13"].I am doing correct way in php ? any other ways to get json object apart from this ?
Use an array for that like this:
$array = array($_POST['cas'], $_POST['casty']);
$final_value = json_encode($array);
Note: no need to create $a and $b.
By adding JSON_FORCE_OBJECT as a 2nd parmeter you'll get key => value data like a normal php array. JSON Arrays don't have keys, therefore most of the time JSON_FORCE_OBJECT is useful.
JSON Array ["data", "data2", "data3"]
JSON Object {0:"data", 1:"data2", 2:"data3"}

json_encode changing array with one value to object

I"m creating a PHP script that handles JSON input (via a $_POST variable). It"s extracts data from the JSON and uploads it to an SQL database. I want the JSON in a particular format:
$object = json_decode('{
"key_a":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}],
"key_b":[{"value_a":10,"value_b":7}],
"key_c":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}]
}',true);
Basically, an object with keys in, each of which should hold an array (no matter what size it is). I use json_decode(json,true) to convert it to an associative array (as opposed to object). I"ve had to add lots of checks in for each of the keys, checking if they"re objects or arrays (as the ASP.net page that the extract comes from converts arrays with single objects in, to objects - removing the array that holds them). The checks then convert them back to arrays, if there"s an object where I"d like an array holding an object:
if(is_object($object["key_b"]))
{
$a = array();
$a[] = $object["key"];
$object["key"] = $a;
}
I then iterate through the array, adding the values to rows in an SQL database. This all works fine, but when converting back to JSON with json_encode, any keys that hold arrays with only one object in, remove the array, and leave just the object under that key:
echo(json_encode($object));
// RETURNED JSON
'{
"key_a":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}],
"key_b":{"value_a":10,"value_b":7},
"key_c":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}]
}'
You see, key_b no longer holds an array, but an object! This is really annoying, as I plan to create a JavaScript script that iterates through the arrays, adding one DOM element (div) for each of the objects.
Why does this happen? Is there any way to keep them as arrays, even if there"s only one object in the array?
I"ve tried:
if(is_object($object["key_b"]))
{
$a = array();
$a[] = array_values($object["key"]);
$object["key"] = $a;
}
and
if(is_object($object["key_b"]))
{
$a = array();
$a[0] = array_values($object["key"]);
$object["key"] = $a;
}
But it seems like nothing prevents json_encode from affecting the JSON in this way.
It"s not hard to get around this - but it means adding one check per key (checking whether it"s an array or value), which is particularly time consuming as the data extract that comes through is really big.
Any advice would be greatly appreciated.
EDIT: changed ' to " in JSON - though, this is only an example I just wrote to show the structure.
EDIT: I'm using references to cut my coding time down, if this changes anything?:
$t =& $object["key_b"];
if(is_object($t))
{
$a = array();
$a[] = $t;
$t = $a;
}
It appears using is_object() on a key of an associative array will not return true. I just knocked up this example, to prove this:
$json = json_decode('{"job_details":{"a":[{"x":5},{"y":23},{"z":18}],"b":{"x":19},"c":[{"x":64},{"y":132}]}}',true);
echo(json_encode($json)."<br><br>");
$t =& $json["job_details"]["b"];
if(is_object($t))
{
$a = array();
$a[] = $t;
$t = $a;
echo("IS OBJECT<br><br>");
}
echo(json_encode($json));
I will find another means of checking what value is held within an associative arrays key.
I was actually trying to find whether the value in the key is an associative array or not (not an object) - I just didn't realise they were different in PHP.
I must just use this custom function:
function is_assoc($array)
{
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
From: How to check if PHP array is associative or sequential?
Which returns true if the value is an associative array.

Put more keys and values into an existing array

I have an array like so:
$json = array('error'=>true);
But I'd like to perhaps add more keys and values to this at a later time. My feeble knowledge tried this:
$json .= array('something'=>'else');
Which doesn't work. I found array_push but it seems this is for just pushing in new values - not keys. How is this achieved so that with 2 separate declarations I end up with the equivalent of:
$json .= array('error'=>true,'something'=>'else');
there are many ways to accomplish this:
$json['keyname'] = 'something
$json[] = 'something' <- numerical incremented key
array_push($json, 'value') <- same as above
$json = array_merge($json, $some_other_array) <- mixes the two arrays together
Just keep in mind that arrays are not strings

Does PHP feature short hand syntax for objects?

In javascript you can easily create objects and Arrays like so:
var aObject = { foo:'bla', bar:2 };
var anArray = ['foo', 'bar', 2];
Are similar things possible in PHP?
I know that you can easily create an array using the array function, that hardly is more work then the javascript syntax, but is there a similar syntax for creating objects? Or should I just use associative arrays?
$anArray = array('foo', 'bar', 2);
$anObjectLikeAssociativeArray = array('foo'=>'bla',
'bar'=>2);
So to summarize:
Does PHP have javascript like object creation or should I just use associative arrays?
For simple objects, you can use the associative array syntax and casting to get an object:
<?php
$obj = (object)array('foo' => 'bar');
echo $obj->foo; // yields "bar"
But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple).
There was a proposal to implement this array syntax. But it was declined.
Update    The shortened syntax for arrays has been rediscussed, accepted, and is now on the way be released with PHP 5.4.
But there still is no shorthand for objects. You will probably need to explicitly cast to object:
$obj = (object) ['foo'=>'bla', 'bar'=>2];
As of PHP 5.4, you can do this:
$array = ['foo'=>'bla', 'bar'=>2];
It's not much shorter, but you'll appreciate it if you need to use a lot of hard coded nested arrays (which isn't altogether uncommon).
If you want an object, you would still need to cast each array:
$object = (object) ['foo'=>'bla', 'bar'=>2];
According to the new PHP syntaxes,
You can use
$array = [1,2,3];
And for associative arrays
$array = ['name'=>'Sanket','age'=>22];
For objects you can typecast the array to object
$object = (object)['name'=>'Sanket','age'=>22];
There is no object shorthand in PHP, but you can use Javascript's exact syntax, provided you use the json_encode and json_decode functions.
The method provided by crescentfresh works very well but I had a problem appending more properties to the object. to get around this problem I implemented the spl ArrayObject.
class ObjectParameter extends ArrayObject {
public function __set($name, $value) {
$this->$name = $value;
}
public function __get($name) {
return $this[$name];
}
}
//creating a new Array object
$objParam = new ObjectParameter;
//adding properties
$objParam->strName = "foo";
//print name
printf($objParam->strName);
//add another property
$objParam->strUser = "bar";
There is a lot you can do with this approach to make it easy for you to create objects even from arrays, hope this helps .
Like the json_decode idea, wrote this:
function a($json) {
return json_decode($json, true); //turn true to false to use objets instead of associative arrays
}
//EXAMPLE
$cat = 'meow';
$array = a('{"value1":"Tester",
"value2":"'.$cat.'",
"value3":{"valueX":"Hi"}}');
print_r($array);

Categories