JSON - using PHP's push_array - php

can someone please explain to me why the first one is working and the second one not? The result is in the second example simply "1".
1.
$c = 0;
$list = array();
foreach ($places as $place) {
$arr = array();
$arr[0] = get_object_vars($place);
$list[$c] = $arr;
$c++;
}
echo json_encode(array("status" => "true", "list" => $list));
2.
$list = array();
foreach ($places as $place) {
array_push($list, get_object_vars($place));
}
echo json_encode(array("status" => "true", "list" => $list));
Sample data for both code samples:
$places = array();
$place = new StdClass;
$place->name = 'first';
$place->location = array('x' => 0.0, 'y' => 0.0);
$places[] = $place;
$place = new StdClass;
$place->name = 'Greenwich Observatory';
$place->location = array('x' => 51.4778, 'y' => 0.0017);
$place->elevation = '65.79m';
$places[] = $place;

In the first case you are adding a key value pair to the array, in the second case just the value. I believe just adding the value SHOULD in fact work, but maybe
foreach ($places as $place) {
array_push($list, array( 0 => get_object_vars($place) );
}
will work better?

Related

Group together array elements

I have an array in PHP:-
$arr = ["BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2"]
Here I want to group together elements based on same ending integer together in json like
$post_data = array(
'0' => array(
'BX_NAME0' => $item_type,
'BX_categoryName0' => $string_key,
'BHA_categories0' => $string_value
),
'1' => array(
'BX_NAME1' => $item_type,
'BX_categoryName1' => $string_key,
'BHA_categories1' => $string_value
),
);
I have Used:- filter_var($key , FILTER_SANITIZE_NUMBER_INT);
to get the integer part of the array elements but don't known how to group them further.
You can do it like below using preg_match():-
$new_array = array();
foreach ($arr as $ar){
preg_match_all('!\d+!', $ar, $matches); //get the number from string
$new_array[$matches[0][0]][$ar] = '';
}
echo "<pre/>";print_r($new_array);
Output:- https://eval.in/715548
It should be something like this:-
$arr = array("BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2");
$post_data = array();
foreach($arr as $value) {
$key = filter_var($value , FILTER_SANITIZE_NUMBER_INT);
if(isset($post_data[$key]) && !is_array($post_data[$key])) {
$post_data[$key] = array();
}
$post_data[$key][] = $value;
}
print_r($post_data);
Tested and works
However, I suggest you use substr() to get the last character of the array item, for performance and stuff..
By using filter_var() method
$arr = ["BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2"];
foreach($arr as $a){
$int = filter_var($a, FILTER_SANITIZE_NUMBER_INT);
$newarr[$int][$a] = '';
}
print_r($newarr);
Output:-https://eval.in/715581

Sorting PHP array(s) based on their initial keys?

I want to sort my initial array(s) that contain many keys and values inside, into array(s) sorted by a specific key, and all the values for that key in a single array based on the key.
So here's the array I have:
$Before = Array(Array("id" => 1, "name" => "Dogs"),
Array("id" => 2, "name" => "Lions"),
Array("id" => 3, "name" => "Tigers"));
And this is the array that I would like to end up with:
$After = Array("ids" => Array(1, 2, 3),
"names" => Array("Dogs", "Lions", "Tigers"));
I hope that makes sense. I found it easier to show you an example, as oppose to describing it.
$after = array(
'ids' => array(),
'names' => array()
);
foreach($before as $row){
$after['ids'][] = $row['id'];
$after['names'][] = $row['name'];
}
var_dump($after);
You can use array_reduce
$After = array_reduce($Before, function ($a, $b) {
$a['ids'][] = $b['id'];
$a['names'][] = $b['name'];
return $a;
});
Live DEMO
Maybe something like:
foreach ($input as $item) {
foreach ($item as $field => $value) {
$result[$field][] = $value;
}
}
var_dump($result);
$After = array();
foreach ($Before as $a) {
$After['ids'][] = $a['id'];
$After['names'][] = $a['name'];
}
This should work :)

Get the array chunk in PHP

Do we have any array function in PHP to get this:
Example:
$array[0] = array("size" => "XL", "color" => "gold");
$array[1] = array("size" => "XLL", "color" => "siver");
$array[2] = array("size" => "M", "color" => "purple");
$color = array();
foreach($arrayas $result)
{
$color[] = $result['color'];
}
I need
$color[0] = "gold";
$color[1] = "silver";
$color[2] = "purple";
Thanks in Advance for your help.
This will do what you're looking for in PHP 5.3+.
$color = array_reduce($array,
function($previous, $new) { $previous[] = $new['color']; return $previous;}
);
If you're on PHP 5.2, you can define a function elsewhere and pass it in:
function getColor($previous, $new) {
$previous[] = $new['color'];
return $previous;
}
$color = array_reduce($array, 'getColor');
Check this out it works fine
$color = array();
foreach($array as $key=>$value)
{
$color[$key] = $value['color'];
}
print_r($color);

Convert multidimensional array to nested set array

im having a little problem i need some help with.
Im trying to convert a multidimensional array into a flatten array with nested set values right and left like so:
$array = {
'id' => 1
'name' => 'john'
'childs' => array(
array(
'id' => 1
'name' => 'jane'
)
)
}
to
$array = {
array(
'id' => 1,
'name' => 'john'
'left' => '1'
'right' => '4'
),
array(
'id' => 1,
'name' => 'jane'
'left' => '2'
'right' => '3'
)
}
Any help is appreciated!
I asked a very similar question and got a result, so thought I'd send it on for you. I realise this is quite an old topic, but still worth getting an answer. I've included my data, but would be easily adapted for yours.
$JSON = '[{"id":1,"children":[{"id":2,"children":[{"id":3},{"id":4}]},{"id":5}]}]';
$cleanJSON = json_decode($JSON,true);
$a_newTree = array();
function recurseTree($structure,$previousLeft)
{
global $a_newTree; // Get global Variable to store results in.
$indexed = array(); // Bucket of results.
$indexed['id'] = $structure['id']; // Set ID
$indexed['left'] = $previousLeft + 1; // Set Left
$lastRight = $indexed['left'];
$i_count = 0;
if ($structure['children'])
{
foreach ($structure['children'] as $a_child)
{
$lastRight = recurseTree($structure['children'][$i_count],$lastRight);
$i_count++;
}
}
$indexed['right'] = $lastRight + 1; // Set Right
array_push($a_newTree,$indexed); // Push onto stack
return $indexed['right'];
}
recurseTree($cleanJSON[0],0);
print_r($a_newTree);
function restructRecursive($array, $left = 1) {
if (isset($array['childs'])) {
$result = array();
foreach ($array['childs'] as $child) {
$result = array_merge($result, restructRecursive($child, $left+1));
}
unset($array['childs']);
}
$array['left'] = $left;
return array_merge(array($array), $result);
}
$newStruct = restructRecursive($oldStruct);
For anyone coming here and looking for a solution, loneTraceur's solution works fine. However, I needed one in OOP, so here is my version of it.
<?php
class NestedSet
{
protected $tree = [];
public function deconstruct($tree, $left = 0)
{
$this->flattenTree($tree, $left);
return $this->tree;
}
protected function flattenTree($tree, $left)
{
$indexed = [];
$indexed['id'] = $tree['id'];
$indexed['_lft'] = $left + 1;
$right = $indexed['_lft'];
if (isset($tree['children']) && count($tree['children'])) {
foreach ($tree['children'] as $child) {
$right = $this->flattenTree($child, $right);
}
}
$indexed['_rgt'] = $right + 1;
$this->tree[] = $indexed;
return $indexed['_rgt'];
}
}
You would run it like this:
$NestedSet = new NestedSet;
$flat = $NestedSet->deconstruct($tree):
This code is based on the other answer.

Dynamic array key in while loop

I'm trying to get this working:
I have an array that gets "deeper" every loop. I need to add a new array to the deepest "children" key there is.
while($row = mysql_fetch_assoc($res)) {
array_push($json["children"],
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
}
So, in a loop it would be:
array_push($json["children"] ...
array_push($json["children"][0]["children"] ...
array_push($json["children"][0]["children"][0]["children"] ...
... and so on. Any idea on how to get the key-selector dynamic like this?
$selector = "[children][0][children][0][children]";
array_push($json$selector);
$json = array();
$x = $json['children'];
while($row = mysql_fetch_assoc($res)) {
array_push($x,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$x = $x[0]['children'];
}
print_r( $json );
Hmmm - maybe better to assign by reference:
$children =& $json["children"];
while($row = mysql_fetch_assoc($res)) {
array_push($children,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$children =& $children[0]['children'];
}
$json = array();
$rows = range('a', 'c');
foreach (array_reverse($rows) as $x) {
$json = array('id' => $x, 'name' => 'start', 'children' => array($json));
}
print_r($json);
If you want to read an array via a string path, split the string in indices, and then you can do something like this to get the value
function f($arr, $indices) {
foreach ($indices as $key) {
if (!isset($arr[$key])) {
return null;
}
$arr = $arr[$key];
}
return $arr;
}

Categories