Help understanding a php function - the meaning of $array[]; the [] part - php

private function jsonArray($object)
{
$json = array();
if(isset($object) && !empty($object))
{
foreach($object as $obj)
{
$json[]["name"] = $obj;
}
}
return $json;
}
We are grabbing an object, and if the conditional is met, we iterate over that object.
Then... I'm lost on this reading... :s
What's the meaning of the [] here?
$json[]["name"] = $obj;
Thanks in advance,
MEM

$json[] adds an element at the end of the array (numeric index). It's the same as having the following code:
$array=array();
$i=0;
foreach($something as $somethingElse)
{
$array[]=$somethingElse;
//is equivalent, in some way, to
$array[$i++]=$somethingElse;
}

That's the equivalent to this:
$json[] = array('name' => $obj);

It adds the contents of $obj to a new field in $json and there in the field "name".
Little example:
$arr = array();
$arr[] = "Hello";
$arr[] = "World!";
Then, $arr will contain:
Array (
0 => "Hello",
1 => "World!"
)
Or, as in your example with another array in the field:
$arr = array();
$arr[]["text"] = "Hello";
$arr[]["text"] = "World!";
Becomes
Array (
0 => Array (
"text" => "Hello"
),
1 => Array (
"text" => "World!"
)
)

$json[] automatically creates a new element at the end of the array - here is an example:
$json[]["name"] = "object1";
$json[]["name"] = "object2";
$json[]["name"] = "object3";
$json[]["name"] = "object4";
And here is what it displays:
Array
(
[0] => Array
(
[name] => object1
)
[1] => Array
(
[name] => object2
)
[2] => Array
(
[name] => object3
)
[3] => Array
(
[name] => object4
)
)

Related

remove duplicate items from object php

{"id":34,"first_name":"xus"}
{"id":34,"first_name":"xus"}
{"id":4,"first_name":"ABC"}
{"id":4,"first_name":"ABC"}
$newlist = [];
$values = [];
foreach ($appointment_list as $key => $value) {
# code...
$values[] = $value['users'];
foreach($values as $val){
$newlist[$val->id]=$values;
}
unset($newlist[$key][$values]);
}
I want to remove duplicate value from object show distinct value base on id and want to count duplicate exist of each id
Expected
id 34 has 2 duplicate
and it should return one object
{"id":34,"first_name":"xus", "count":2}
something like that
You can use array_reduce
$arr = array(
array("id" => 34,"first_name" => "xus"),
array("id" => 34,"first_name" => "xus"),
array("id" => 4,"first_name" => "ABC"),
array("id" => 4,"first_name" => "ABC"),
);
$result = array_reduce($arr, function($c, $v){
if ( !isset( $c[$v["id"]] ) ) {
$c[$v["id"]] = $v;
$c[$v["id"]]["count"] = 1;
} else {
$c[$v["id"]]["count"]++;
}
return $c;
}, array());
$result = array_values( $result );
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[id] => 34
[first_name] => xus
[count] => 2
)
[1] => Array
(
[id] => 4
[first_name] => ABC
[count] => 2
)
)
The simplest way of doing this is to create an empty array and map your objects using "id" as a key.
Here's the working snippet
<?php
$objectsRaw = [];
$objectsRaw[] = '{"id":34,"first_name":"xus"}';
$objectsRaw[] = '{"id":34,"first_name":"xus"}';
$objectsRaw[] = '{"id":4,"first_name":"ABC"}';
$objectsRaw[] = '{"id":4,"first_name":"ABC"}';
# decode the json objects into PHP arrays
$objects = array_map(
function($objectJson) {
$object = json_decode($objectJson, true);
return $object;
},
$objectsRaw
);
# map the objects
$result = [];
foreach($objects as $object) {
if (array_key_exists($object['id'], $result) === false) {
$object['count'] = 1;
$result[$object['id']] = $object;
continue;
}
$result[$object['id']]['count']++;
}
# encode result
$resultRaw = array_map('json_encode', $result);
# would look like
# Array
# (
# [34] => {"id":34,"first_name":"xus","count":2}
# [4] => {"id":4,"first_name":"ABC","count":2}
# )
# reset array keys (if you need this)
$resultRaw = array_values($resultRaw);
# would look like
# Array
# (
# [0] => {"id":34,"first_name":"xus","count":2}
# [1] => {"id":4,"first_name":"ABC","count":2}
# )

How to transfer one array to another array in php

I have a simple Two array
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
When I print this arrays it should be like following:
Array
(
[0] => Array
(
[Peter] => 22
[Clark] => 32
[John] => 28
)
)
Array
(
[0] => Array
(
[demo] => 22
)
)
But I want to create third array which will be show demo kye value into first array like following:
Array
(
[0] => Array
(
[Peter] => 22
[Clark] => 32
[John] => 28
[demo] => 22
)
)
Can we do two array into single array in PHP like Above
Not sure what are you trying to achieve here...little more context would be helpful. But this is how you can do this,
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$result[] = array_merge($ages[0],$ages1[0]);
This would do the job.
<?php
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$output = prepend_array($ages,$ages1);
print_r($output);
// Function to prepend arrays
function prepend_array()
{
$num_args = count(func_get_args());
$new_array = array();
foreach (func_get_args() as $params){
foreach($params as $out_key => $param)
{
foreach($param as $key => $value)
$new_array[$out_key][$key] = $value;
}
}
return $new_array;
}

PHP looping through array and appending to object

I have array of objects like so;
Array
(
[0] => stdClass Object
(
[Job] => stdClass Object
(
[ID] => 123
[Name] => Foo
)
)
[1] => stdClass Object
(
[Job] => stdClass Object
(
[ID] => 456
[Name] => BAR
)
)
)
I need to loop through the array and append some additional information to the object like 'Status', but I'm having some issues.
foreach($arrJobs as $key => $val) {
$arrJobs[$key]->Job->Status = new StdClass;
$arrJobs[$key]->Job->Status = $myStatus;
}
This appears to work, but I get the following warning;
Warning: Creating default object from empty value in...
Yes, create an object first. You cannot assign properties of null. That's why you need an instance of stdClass, php's generic empty class.
$arrJobs[$key] = new stdClass;
$arrJobs[$key]->foo = 1;
// And/or see below for 'nested' ...
$arrJobs[$key]->bar = new stdClass;
$arrJobs[$key]->bar->foo = 1;
According to my understanding to you question you just need to append properties to your existing objects. Don't create new objects in your loop
you just need this
foreach ($arrJobs as $obj)
{
$obj->job->status = $myStatus;
}
See the full code :
<?php
$obj1 = new \stdClass();
$obj1->job = new \stdClass();
$obj1->job->id = 123;
$obj1->job->name = "foo";
$obj2 = new \stdClass();
$obj2->job = new \stdClass();
$obj2->job->id = 456;
$obj2->job->name = "bar";
$array = [$obj1,$obj2];
var_dump($array);
foreach ($array as $obj)
{
$obj->job->status = "the status";
//add any properties as you like dynamicly here
}
echo "<br>\nafter<br>\n";
var_dump($array);
exit;
Now $obj1 and $obj2 has the new property 'status' ,see that demo : (https://eval.in/833410)
for ($i = 0; $i < count($arrJobs); $i++)
{
$arrJobs[$i]->Job->Status = new stdClass;
// other operations
}
Try this,
PHP
<?php
// Sample object creation.
$array = [];
$array = [0 => (object) ['Job'=>(object) ['ID'=>123, 'Name' => 'Foo']]];
foreach($array as $val) {
$val->Job->Status = (object) ['zero' => 0,'one' => 1]; // Status 0 and 1.
}
echo "<pre>";
print_r($array);
?>
Output
Array
(
[0] => stdClass Object
(
[Job] => stdClass Object
(
[ID] => 123
[Name] => Foo
[Status] => stdClass Object
(
[zero] => 0
[one] => 1
)
)
)
)

php multi-dimensional array provides three levels of depth instead of two

When I execute the code below:
Code:
<?php
$data = array();
$jim = array('Jim'=>1);
$bob = array('Bob'=>1);
$data['abc'][] = $jim;
$data['abc'][] = $bob;
print_r($data);
?>
I receive the following output:
Array
(
[abc] => Array
(
[0] => Array
(
[Jim] => 1
)
[1] => Array
(
[Bob] => 1
)
)
)
What I am expecting is the following output:
Array
(
[abc] => Array
(
[Jim] => 1
[Bob] => 1
)
)
How can I achieve this? To rephrase the question, how can I keep it to a single sub-array per a supplied key?
$data = array();
$jim = array('Jim'=>1);
$bob = array('Bob'=>1);
$data['abc'] = array_merge($jim, $bob);
print_r($data);
You are creating array ($data['abc']) which contains an array ([]) of arrays($jim, $bob)
It's the same as writing:
$data['abc'][0] = array('jim' => 1);
$data['abc'][1] = array('bob' => 1);
What you want is probably:
$data['abc'] = array();
$data['abc'] = array_merge($data['abc'], $jim, $bob);
Jim and Bob are array indexes by your own declaration, you have to change them first
<?php
$data = array();
$data['abc']["Jim"] =1;
$data['abc']["Bob"] = 2;
print_r($data);
?>
Demo

PHP array to tree array

I have a problem I cannot fix. I have 2 arrays and a string. The first array contains the keys the second one should use. The first one is like this:
Array
(
[0] => foo
[1] => bar
[2] => hello
)
Now I need a PHP code that converts it to the second array:
Array
(
[foo] => Array
(
[bar] => Array
(
[hello] => MyString
)
)
)
The number of items is variable.
Can someone please tell me how to do this?
You should use references to solve this problem:
$a = array (0 => 'foo', 1 => 'bar', 2 => 'hello' );
$b = array();
$ptr = &$b;
foreach ($a as $val) {
$ptr[$val] = Array();
$ptr = &$ptr[$val];
}
$ptr = 'MyString';
var_dump($b);
All you need is :
$path = array(
0 => 'foo',
1 => 'bar',
2 => 'hello'
);
$data = array();
$t = &$data;
foreach ( $path as $key ) {
$t = &$t[$key];
}
$t = "MyString";
unset($t);
print_r($data);
See Live Demo

Categories