php make a json object not working as expected - php

This is my code:
$amenitiesObject = array('parameter-amenities' => array('value' => $amenities));
$buildingObject = array('parameter-building' => array('value' => $building));
$data = array($amenitiesObject, $buildingObject);
$post_data = json_encode($data, JSON_FORCE_OBJECT);
return $post_data;
the result is:
{"0":{"parameter-amenities":{"value":""}},"1":{"parameter-building":{"value":""}}}
while i was hoping for this:
{"parameter-amenities":{"value":""},"parameter-building":{"value":""}}
what is my mistake please?

While #fusion3k's comment is correct and doing $data = array_merge( $amenitiesObject, $buildingObject ); fixes it, I'd like to explain it a little further so you can avoid this type of scenario.
When you do $data = array($amenitiesObject, $buildingObject);, you are not creating a merge of both arrays, you are creating an array with index 0 equals to $amenitiesObject and index 1 equals to $buildingObject, the equivalent of doing :
array(0 => $amenitiesObject, 1 => $buildingObject);
So the json_encode part is working as expected.
When you use array_merge, you maintain only ONE array, that is a combination on both arrays, so you have the expected result.

Related

Is there a cleaner way to send an array from a controller to a function, model or view?

Is there a more compact way to send an array to a function?
Here's what I'm currently doing:
$data = array(
'id' => '1'
);
$result = $this->Tests_model->DoSomething($data);
What I'd like to do is just:
$result = $this->Tests_model->DoSomething(array('id' => '1'));
or
$result = $this->Tests_model->DoSomething(('id' => '1'));
...but I can't seem to format the data inside the ( and ). I still want to pass an array, for better code-reuse. Is there a way to do this?
This line
$result = $this->Tests_model->DoSomething(array('id' => '1'));
is completely valid and can be used.
You need to change the third example to make it work. What you're looking for is
$result = $this->Tests_model->DoSomething(['id' => '1']);
The syntax ['id' => '1'] is just another way of writing array('id' => '1') they produce the exact some thing.
One last way to create an array and add a key/value pair to it is like this.
$data['id'] = '1'; //assigns a value of '1' to the key 'id' in an array named $data.
The above is just alternate syntax for writing.
$data = array('id' => '1');
None of these variations on syntax is better or worse other than in terms of "readability" which is often a matter of opinion.
Everything you could want to know about arrays in the PHP Documentation.

PHP Prepend two elements to associative array

I have the following array, I'm trying to append the following ("","--") code
Array
(
[0] => Array
(
[Name] => Antarctica
)
)
Current JSON output
[{"Name":"Antarctica"}]
Desired output
{"":"--","Name":"Antarctica"}]
I have tried using the following:
$queue = array("Name", "Antarctica");
array_unshift($queue, "", "==");
But its not returning correct value.
Thank you
You can prepend by adding the original array to an array containing the values you wish to prepend
$queue = array("Name" => "Antarctica");
$prepend = array("" => "--");
$queue = $prepend + $queue;
You should be aware though that for values with the same key, the prepended value will overwrite the original value.
The translation of PHP Array to JSON generates a dictionary unless the array has only numeric keys, contiguous, starting from 0.
So in this case you can try with
$queue = array( 0 => array( "Name" => "Antarctica" ) );
$queue[0][""] = "--";
print json_encode($queue);
If you want to reverse the order of the elements (which is not really needed, since dictionaries are associative and unordered - any code relying on their being ordered in some specific way is potentially broken), you can use a sort function on $queue[0], or you can build a different array:
$newqueue = array(array("" => "--"));
$newqueue[0] += $queue[0];
which is equivalent to
$newqueue = array(array_merge(array("" => "--"), $queue[0]));
This last approach can be useful if you need to merge large arrays. The first approach is probably best if you need to only fine tune an array. But I haven't ran any performance tests.
Try this:
$queue = array(array("Name" => "Antarctica")); // Makes it multidimensional
array_unshift($queue, array("" => "--"));
Edit
Oops, just noticed OP wanted a Prepend, not an Append. His syntax was right, but we was missing the array("" => "--") in his unshift.
You can try this :
$queue = array("Name" => "Antarctica");
$result = array_merge(array("" => "=="), $queue);
var_dump(array_merge(array(""=>"--"), $arr));

PHP Dynamic Nested Associative Array

I have an associative array which is generated dynamically with the values from database. When I print the whole array, it gives something like this when we put print_r($array).
Array ( [95a5c80811239526fb75cbf31740cc35] => Array ( [product_id] => 2324) )
When I echo like this,
echo $array['95a5c80811239526fb75cbf31740cc35']['product_id'];
it gives me product id.
But the problem is, the code '95a5c80811239526fb75cbf31740cc35' changes dynamically everytime. I want to echo the product id irrespective of this code.
I tried
$array[]['product_id'];
$array['']['product_id'];
But not working. Can anyone help me? Please ask me if you have any doubts.
You can use reset() in this case:
$array = array(
'95a5c80811239526fb75cbf31740cc35' => array( // dynamic
'product_id' => 2324
),
);
$value = reset($array); // set pointer to first element
echo $value['product_id']; // 2324
Assuming that the code is always the first element in the array:
$array[0]['product_id'];
If you collectively want all of the product ID's:
foreach($array as $product){
$productIds[] = $product['product_id'];
}
// $productIds is now what $array was, but without the codes, so the product_id's are the first elements.
You can use for each for this so that you can get the value of product Id
$array = Array ( [95a5c80811239526fb75cbf31740cc35] => Array ( [product_id] => 2324) )
foreach($array as $product){
echo $product['product_id'];
}
This would get your desired o/p
IF you are getting problem using Associative array then you can first convert it into numeric as follows
$arr=array( 'first' => array( 'product_id' => 2324) );
$arrr=array_values($arr);
echo $arrr[0]['product_id'];
Output:
2324
Hope this helps and to know about array_values go here
Depending on your situation, there are few possible solutions:
$array = array_shift(array_values(
Array(
'95a5c80811239526fb75cbf31740cc35' =>
Array(
'product_id' => 2324
)
)));
echo $array['product_id']; // 2324
Another solution, probably more efficient:
echo array_shift(array_slice($array, 0, 1)); // 2324
For PHP 5.4+ you could go with:
echo array_values($array)[0]; // 2324
$array[0]['product_id'];
Should do the trick.

MongoDB PHP using $in with array

I'm using MongoDB and PHP and trying to do a $in based on a generated array.
When I specify the same array manually, it works, but when I build it, it return any results with the same data.
There's what I have:
$settings = array();
foreach($items as $item) {
$settings[] = $item['id'];
}
//Settings is the same as this
$setting2 = array(1,2,3,4,5,6,7,8);
//This returns no results
$cursor = $collection->find(array('status' => 0, 'sid' => array('$in' => $settings)));
//This does return results
$cursor = $collection->find(array('status' => 0, 'sid' => array('$in' => $setting2)));
I've checked using
$cursor->info()
And the items in the array are the same.
Any ideas what I'm doing wrong?
Thanks!
It's likely that the data types of the numbers are not the same. Try using var_dump() on the built array, and the specified array. You'll probably see one has them as numbers in a string, and the other as simple integers.

json_encode children items?

How can I use php json_encode to produce the following from an array?
{"issue":{"project_id":"Test Project","subject":"Test Issue"}}
I've been trying for the last 40 mins but I can't get it working for the life of me.
The best I can do is:
$arr = array ("project_id"=>"Baas","subject"=>"Test Issue");
echo json_encode($arr); // {"project_id":"Baas","subject":"Test Issue"}
The problem is making "issue" parent. Any hint on how to accomplish this?
Thanks!
The output you want is essentially an associative array nested in another associative array. So, create that data structure, then encode it.
$child_arr = array("project_id" => "Baas", "subject" => "Test Issue");
$parent_arr = array("issue" => $child_arr);
echo json_encode($parent_arr);
Or, if we're in a one-liner mood today:
$arr = array("issue" => array("project_id" => "Baas", "subject" => "Test Issue"));
echo json_encode($arr);
$arr = array ("issue" => array("project_id"=>"Baas","subject"=>"Test Issue"));

Categories