This question already has answers here:
Help editing JSON to make an array rather than a 'dictionary'
(2 answers)
Closed 9 years ago.
I am having arrays from my PHP
{"lista":[{"Grad":"Beograd"},{"Grad":"Novi_Sad"},{"Grad":"Beograd"},{"Grad":"Novi_Sad"},{"Grad":"Beograd"},{"Grad":"Beograd"},{"Grad":"Beograd"},{"Grad":"Kragujevac"},{"Grad":"Kragujevac"},{"Grad":"Beograd"},{"Grad":"Kragujevac"},{"Grad":"Beograd"}]}
and when I use:
$arr = array_flip(array_map('serialize', $rows));
$lista = array_map('unserialize', array_flip($arr));
echo json_encode((object) array('lista' => $lista));
I am getting
{"lista":{"19":{"Grad":"Beograd"},"18":{"Grad":"Novi_Sad"},"20":{"Grad":"Kragujevac"}}}
Question is how can I remove this numbers that are in front of my arrays?
Try changing
echo json_encode((object) array('lista' => $lista));
to
echo json_encode((object) array('lista' => array_values($lista)));
Note : not tested
I think you need to populate the array as in the example in the documentation in the php manual:
http://php.net/manual/en/function.json-encode.php
From PHP Site:
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
The above example will output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
apply array_values before encoding into Json_encode
$lista = array_values(array_map('unserialize', array_flip($arr)));
echo json_encode((object) array('lista' => $lista));
Related
This question already has answers here:
print an array as code
(4 answers)
Closed 2 years ago.
for very special purpose I need to transform PHP array into PHP code. I will try to explain what I mean in code below:
$a = array('a' => 'abc', 'path' => INCLUDE_DIR.'/file.txt', 'number' => 1234);
$php_code = some_magic_function($a);
echo $php_code; // outputs: "array('a' => 'abc', 'path' => '/path/to/file.txt', 'number' => 1234)"
So it would write back array as PHP code. I can not find any library that would help me with this.
Any ideas or hints ? Thanks in advance.
I think you want to print the array as a string, in the exact format it would be written in your code.
If so, then the var_export() function is what you need, e.g. something like this:
$a = array('a' => 'abc', 'path' => '/file.txt', 'number' => 1234);
$str = var_export($a, true);
echo $str;
Demo: http://sandbox.onlinephpfunctions.com/code/0b1da8fc0199a34539a55313680e982f9fddd14f
This question already has answers here:
How to access and manipulate multi-dimensional array by key names / path?
(10 answers)
Closed 3 years ago.
I am trying to pass an index of associative array stored in a variable:
$a = array(
'one' => array('one' => 11, 'two' =>12),
'two' => array('one' => 21, 'two' => 22)
);
$s = "['one']['two']"; // here I am trying to assign keys to a variable for a future use
echo $a[$s]; // this usage gives error Message: Undefined index: ['one']['two']
echo $a['one']['two']; // this returns correct result (12)
The same I am trying to do within the object:
$a = array(
'one' => (object)array('one' => 11, 'two' =>12),
'two' => (object)array('one' => 21, 'two' => 22)
);
$a = (object)$a; // imagine that I receive this data from a JSON (which has much sophisticated nesting)
$s = 'one->two'; // I want to access certain object property which I receive from somewhere, hence stored in a variable
echo $a->$s; // produces error. Severity: Notice Message: Undefined property: stdClass::$one->two
echo $a->one->two; // gives correct result ("12")
How do I properly use a variable to access a value as mentioned in above examples?
Note: wrapping these into Curly brackets (i.e. complex syntax) did not work in both cases.
I assume you manually typed the ['one']['two'] part and there is no reason for it to look like that.
The by far simplest method is to explode the array indexes and loop them and that way "dig" in to the array.
$a = array(
'one' => array('one' => 11, 'two' =>12),
'two' => array('one' => 21, 'two' => 22)
);
$s = "one,two";
$res = $a;
foreach(explode(",", $s) as $item){
$res = $res[$item];
}
echo $res; // in this case echo works. But you should perhaps have if array print_r
https://3v4l.org/LeUFW
If you actually do have the one two like that then you can make it an array like this:
$s = "['one']['two']";
$s = explode("][", str_replace("'", "", trim($s, "[]")));
// $s is now an array ['one', 'two']
https://3v4l.org/YUjbn
The only solution seems to be eval() IF you trust the contents of $s:
eval( 'echo $a'.$s.';' );
This question already has answers here:
Best way to create an empty object in JSON with PHP?
(4 answers)
Closed 6 years ago.
I have this array:
$array = [
"stored_fields" => ["id"],
"match_all" => []
];
I want:
{"stored_fields":["id"],"match_all":{}}
But, When I call:
echo json_encode($array);
I got:
{"stored_fields":["id"],"match_all":[]}
If I use:
echo json_encode($array, JSON_FORCE_OBJECT);
I got:
{"stored_fields":{"0":"id"},"match_all":{}}
What I can do?
There might be a better way, but you can just force an object:
$array = [
"stored_fields" => ["id"],
"match_all" => (object)[]
];
You could also use (object)null. Anything else will result in {"scalar":someting}. Another option is new stdClass.
This question already has answers here:
Retrieving array keys from JSON input
(7 answers)
Closed 8 years ago.
I have created a simple json string to decode into a data array, but I am very confused about how to iterate through the array once it is decoded:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$data = json_decode($json, true);
for ($j = 0; $j < count($data); $j++) {
echo "$j: $data[$j]<br>";
}
?>
I can't seem to get this code to work because it is saying that every offset is undefined, so I think the trouble stems from my understanding of what an array looks like once it has been decoded.
When I do a var_dump(json_decode($json, true)), I get this result:
array (size=5)
'a' => int 1
'b' => int 2
'c' => int 3
'd' => int 4
'e' => int 5
So what does this mean exactly? Are the array indexes 'a', 'b', 'c', 'd', and 'e' respectively? If so, then how can I iterate through each of these to print out all of their values?
Arrays in PHP are not the same as arrays in JavaScript (or Json). However, what you're looking at here:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Is not actually a Json array, but a Json object. a, b, c, d, and e are properties of that object (which are a bit like indexes in a PHP array).
To iterate through the properties of this object, you can use a foreach loop:
$data = json_decode($json, true);
foreach ($data as $key => $value) {
echo "$key: $value<br>";
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Converting words to numbers in PHP
I need a function to convert textual numbers to numbers.
For example: convert("nine") outputs 9
I know I could write a function like for example if ($number == "one") { $number = 1; } etc...
but that would be a lot of work.
Use the switch statement.
Use a lookup table like this:
$numbers = array(
'zero' => 0,
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
'seven' => 7,
'eight' => 8,
'nine' => 9
);
$digit = strtolower($digit);
if (isset($numbers[$digit])) {
$digit = $numbers[$digit];
}
Note I use strtolower just in case. Of course, this solution would be impractical for anything over a couple dozen. Beyond that, you'll need some sort of parser.