So I've a json string and an array like so :
$json_str = '{"key1":["val11", "val12", "val13"], "key2":"val2"}';
$delete_keys = array("val12");
I want to delete the values present in delete_keys from json_str['key1']. So I did the following:
$json_arr = json_decode($json_str, true);
$key1 = $json_arr['key1'];
foreach ($delete_keys as $key) {
$index = array_search($key, $key1);
if (isset($index))
unset($key1[$index]);
unset($index);
}
$json_arr['key1'] = $key1;
$json_str = json_encode($json_arr);
print $json_str;
Now the result I expected for json_str is this
{"key1":["val11", "val13"], "key2":"val2"}
But instead I get this
{"key1":{"0":"val11", "2":"val13"}, "key2":"val2"}
It works as I expected if I delete the last key though. Can someone please tell me how to get the former as the json string instead of the latter.
You should reindex array with array_values().
If keys in the array are not sequential it is an associative array.
There is an example of this phenomenon on the PHP documentation for json_encode, labelled with "Sequential array with one key unset": http://php.net/manual/en/function.json-encode.php
Reproduced here:
$sequential = array("foo", "bar", "baz", "blong");
// ...
unset($sequential[1]);
var_dump(
$sequential,
json_encode($sequential)
);
// Outputs: string(33) "{"0":"foo","2":"baz","3":"blong"}"
In order for the keys to remain sequential, you can re-number them using array_values:
$sequential = array("foo", "bar", "baz", "blong");
// ...
unset($sequential[1]);
$sequential = array_values( $sequential );
var_dump(
$sequential,
json_encode($sequential)
);
// Outputs: string(21) "["foo","baz","blong"]"
Related
I have a string = "Name":"Susan","Age":"23","Gender":"Male";
How to store them in an array so that I can echo the value for example:
echo $array['Name']
or
echo $array['Age']
Thanks
If your string is already:
"Name":"Susan","Age":"23","Gender":"Male"
That's almost JSON, so you can just enclose it in curly brackets and convert it to turn that into an array:
$decoded = (Array)json_decode('{'.$str.'}');
json_decode() normally outputs an object, but here we're casting it to an array. This is not required, but it changes how you have to access the resulting elements.
This would render the following associative array:
array(3) {
["Name"]=>
string(5) "Susan"
["Age"]=>
string(2) "23"
["Gender"]=>
string(4) "Male"
}
Associative Arrays in PHP are what you need to achieve your task. In PHP array() are actually ordered maps i.e. associates values with a key Here is an example. An associative array is an array where each key has its own specific value. Here's an example.
$values = array("Name"=>"Susan", "Age"=>"23", "Gender"=>"Male");
echo $values['Name'];
echo $values['Age'];
echo $values['Gender'];
You can store string as json
$json = '{"Name":"Susan","Age":"23","Gender":"Male"}';
$array = json_decode($json, true);
var_dump($array);
The manual specifies the second argument of json_decode as:
assoc
When TRUE, returned objects will be converted into associative arrays.
https://stackoverflow.com/a/18576902/5546916
Try below snippet
$string = "Name":"Susan","Age":"23","Gender":"Male";
//explode string with `,` first
$s = explode(",",$string); // $s[0] = "Name":"Susan"....
$array = array();
foreach($s as $data){
$t = array();
$t = explode(":",$data); //explode with `:`
$array[$t[0]] = $t[1];
}
echo $array["name"];
I am being passed inconsistent data. The problem is the individual rows of $data_array are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order_array, create a new $data_array_new by reordering the data in each "row" into the same sequence as $order_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
$data_array_new = [];
foreach ($data_array as $index => $data) {
$data_array_new[$index] = [];
foreach ($order_array as $key) {
if (isset($data[$key])) {
$data_array_new[$index][] = $data[$key];
} else {
$data_array_new[$index][] = 'NA';
}
}
}
You can view the original incoming data here: https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,tsla,ge&types=quote,earnings,stats
Here is the answer from : Andreas
Use json_decode on the string with the second parameter true and you get a associative array as output.
$url = "https://api.iextrading.com/1.0/stock/market/batch?
symbols=aapl,tsla,ge&types=quote,earnings,stats";
$arr = json_decode(file_get_contents($url), true);
Var_dump($arr);
See here;
I copied the string from the page and posted it as $str.
https://3v4l.org/duWrI
Two steps is all that is needed.
well, i have 2 variables
$variable1 = "123";
$variable2 = "321";
both variables are calculated by other methods and may vary due to change of circumstances, now i want to put these values in a single array for displaying, what i want is something like this
$array = ($variable1, $variable2)
and print like(in IDE)
array([0]=>123 [1]=>321)
both 123 and 321 are representations of variable values.
i tried compact() function but it gave me something weird, i tried make these two variables an array with only one element and merge them into one array but in fact i have many variables and it's infeasible to do this for every one of them.....please show me how i can do it and explain in detail the mechanism behind it, thank you very much.
There are several ways to do what you want.
You can use one of examples below :
// Define a new array with the values
$array1 = array($variable1, $variable2);
// Or
$array2 = [$variable1, $variable2];
// Debug
print_r($array1);
print_r($array2);
// Define an array and add the values next
$array3 = array();
$array3[] = $variable1;
$array3[] = $variable2;
// Debug
print_r($array3);
// Define an array and push the values next
// http://php.net/manual/en/function.array-push.php
$array4 = array();
array_push($array4, $variable1);
array_push($array4, $variable2);
// Debug
print_r($array4);
Just use the array function to get the values into one array.
$var1 = "123";
$var2 = "321";
$array = array($var1,$var2);
var_dump($array); returns:
array (size=2)
0 => string '123' (length=3)
1 => string '321' (length=3)
Or another example on how you could do it is:
$array = array();
$array[] = myFunction(); //myFunction returns a value and by using $array[] you can add the value to the array.
$array[] = myFunction2();
var_dump($array);
Here is your answer
$variable1 = "123";
$variable2 = "321";
$arr =array();
array_push($arr,$variable1);
array_push($arr,$variable2);
echo '<pre>';
print_r($arr);
Hope this will solve your problem.
As you want to put these item in array
First you have to initialize a variable
$newArray = []
After that you have to store the value in array which can be done by this
$newArray[] = $variable1;
// OR BY
array_push($newArray, $variable1);
They both are same it push the data to the end of the array
So your code will be like this
$newArray = []
$newArray[] = $variable1;
$newArray[] = $variable2;
If you want to do it in loop then do somthing like this
$newArray = []
foreach($values as $value){
$newArray[] = $value;
}
If there is a fix value then you can do like this
$newArray = [$variable1, $variable2];
//OR BY
$newArray = array($variable1, $variable2);
Both are same
And to print the value use
print_r($newArray);
Hope this will help
I have two arrays containing repeating values:
$test1 = Array(
"blah1",
"blah1",
"blah1",
"blah1",
"blah2"
);
$test2 = Array(
"blah1",
"blah1",
"blah1",
"blah2"
);
I am trying to get array difference:
$result = array_diff($test1,$test2);
echo "<pre>";
print_r($result);
I need it to return array with single value blah1, yet it returns empty array instead...
I suspect it has something to do with fact there are duplicate values in both arrays, but not sure how to fix it...
Please help!!
EDIT:
End up writing this function to do the trick:
function subtract_array($array1,$array2){
foreach ($array2 as $item) {
$key = array_search($item, $array1);
unset($array1[$key]);
}
return array_values($array1);
}
array_diff compares the first array to the other array(s) passed as parameter(s) and returns an array, containing all the elements present in the first array that are not present in any other arrays. Since $test1 and $test2 both contain "blah1" and "blah2", and no other values, actually, the expected behavior of array_diff is the one that you have experienced, that is, to return an empty array, since, there is no element in $test1 which is not present in $test2.
Further read. Also, read some theory to understand what you are working with.
Spotted a problem with Acidon's own solution. The problem comes from the fact that unset($array[false]) will actually unset $array[0], so there needs to be an explicit check for false (as David Rodrigues pointed out as well.)
function subtract_array($array1,$array2){
foreach ($array2 as $item) {
$key = array_search($item, $array1);
if ( $key !== false ) {
unset($array1[$key]);
}
}
return array_values($array1);
}
Some examples
subtract_array([1,1,1,2,3],[1,2]); // [1,1,3]
subtract_array([1,2,3],[4,5,6]); // [1,2,3]
subtract_array([1,2,1],[1,1,2]); // []
subtract_array([1,2,3],[]); // [1,2,3]
subtract_array([],[1,1]); // []
subtract_array(['hi','bye'], ['bye', 'bye']); // ['hi']
so I have this variable $_GET which receives the value such as
set=QnVzaW5lc3M=|RmluYW5jZQ==
The values are base64 enconded using base64_encode() and then separated by a delimiter '|'. I'm using implode function to generate the value of the set variable.
Now, the question is, how can I get the values from the set variable into an array and base64 decode them as well ?
Any suggestions are welcome.
I tried this :-
$test = array();
$test = explode('|', $_GET['set']);
var_dump($test);
This throws the value which is not usable.
But this made no difference.
$data = 'QnVzaW5lc3M=|RmluYW5jZQ==';
$result = array_map(
'base64_decode',
explode('|', $data)
);
var_dump($result);
This should work using foreach:
// Set the test data.
$test_data = 'QnVzaW5lc3M=|RmluYW5jZQ==';
// Explode the test data into an array.
$test_array = explode('|', $test_data);
// Roll through the test array & set final values.
$final_values = array();
foreach ($test_array as $test_value) {
$final_values[] = base64_decode($test_value);
}
// Dump the output for debugging.
echo '<pre>';
print_r($final_values);
echo '</pre>';
The output is this:
Array
(
[0] => Business
[1] => Finance
)