I'm having problems translating my associative array that I create in jQuery to something I can access and use in PHP.
I use the following to build an associate array:
var colors = {};
$(this).find('input[name="color_id"]').each(function() {
var color_entry_id = $(this).val();
colors[color_entry_id] = jQuery.makeArray($(this).siblings(".colors." + $(this).val()).find(".img_color a.selected").map(function() {
return $(this).css("background-color");
}));
});
Basically, the above code should return something of the form:
colors = {
"{{ color_entry_id }}": [array of string rgb values]
}
I then send it to my PHP script with the following:
$.post(
"test.php",
{ "edit_colors": JSON.stringify(colors) },
...
);
In my PHP, I want to be able to grab the array corresponding to a {{ color_entry_id }} and loop through the values to use in an update query. The following is my PHP code:
$check_colors = array(
"rgb(204, 51, 51)" => "red",
"rgb(102, 153, 204)" => "sky_blue",
"rgb(0, 204, 51)" => "lime_green",
"rgb(0, 102, 0)" => "dark_green",
"rgb(153, 0, 0)" => "burgandy",
"rgb(255, 102, 51)" => "orange",
...
);
$colors = json_decode($_POST['edit_colors']);
foreach($images as $color_entry => $image_link) {
$update_color_query = "UPDATE color SET ";
foreach(array_keys($check_colors) as $color) {
if(in_array($color, $colors[$color_entry])) {
$update_color_query .= $check_colors[$color] . "=1, ";
} else {
$update_color_query .= $check_colors[$color] . "=0, ";
}
}
$update_color_query .= "image_url='$image_link' WHERE id=$color_entry";
mysql_query($update_color_query);
}
In the above code, images is a separate array with corresponding {{ color_entry_id }}s and image links as well. $check_colors is a PHP hardcoded associative array of rgb values to human readable colors. My problem is that the link:
in_array($color, $colors[$color_entry])
throws a "Fatal error: cannot use type stdClass as array" because $colors[$color_entry] is not becoming the two dimensional array I'm trying to get it to be. So anyone know what I am doing wrong and how I can get this two dimensional array to loop through in my PHP code?
The error is exactly what it says: You can't use an OBJECT as an ARRAY. When you use json_decode, it defaults to an object. You need it to be an associative array.
So change it to this:
$colors = json_decode($_POST['edit_colors'], true);
Now, you can iterate through $colors as you need.
Related
I cannot figure out how to take a list of associative arrays from a json file and convert it into a php indexed array of associative arrays, and then access the values nested in the associative arrays
Here is the json file
[
{
"homeTeam":"team1",
"homeScore":"00",
"awayTeam":"team2",
"awayScore":"00",
"gameProgression": "Not Started"
},
{
"homeTeam":"team1",
"homeScore":"00",
"awayTeam":"team2",
"awayScore":"00",
"gameProgression": "Not Started"
}
]
And the php code I have been trying to use
$gameFile = file_get_contents("currentGames.json");
$gameFileReady = json_decode($gameFile,true);
$gameArray = array_keys($gameFileReady);
if ($gameArray[0]['gameProgression'] != "Not Started") {
--code--
};
Thanks in advance
array_keys is just going to give you something like Array ( [0] => 0 [1] => 1 ) in this code. So it is unnecessary to achieve what you want.
Simply remove that line and do:
$gameFile = file_get_contents("currentGames.json");
$gameArray = json_decode($gameFile,true);
if (!isset($gameArray[0]['gameProgression'])) {
die('an error occurred');
}
if ($gameArray[0]['gameProgression'] != "Not Started") {
echo 'something';
};
The isset is just for good measure but doesn't change how you access the array item.
I have a database of zip codes from The Zip Code Database Project that came as a .csv file. I converted it to json and it has no key for each array, they look like this:
[
{
"zipcode": 35004,
"state abbreviation": "AL",
"latitude": 33.606379,
"longitude": -86.50249,
"city": "Moody",
"state": "Alabama"
}
]
I have figured out how to search all of the arrays and locate a matching zip code but I can't figure out how to make that search return data about the array that it found it in.
I can search like this:
$filename = './assets/data/zips.json';
$data = file_get_contents($filename);
$zipCodes = json_decode($data);
$inputZip = 55555;
foreach ($zipCodes as $location) {
if ($inputZip == $location->zipcode) {
echo "Success";
}
}
Can anyone tell me how I can use this search (or a better idea) to store the latitude and longitude associated with the searched zip code to two variables? I have wasted nearly my whole weekend on this so any and all help is greatly appreciated.
Also, I have no issue using the raw csv file to perform this function, I just couldn't get as far as I did with json.
Thanks everyone!
To find out the index of an array by a property of the array items, use array_column to get just the values of that column/property, then use array_search to find the index.
<?php
$inputZip = 35004;
$index = array_search($inputZip, array_column($zipCodes, 'zipcode')); // 0
print_r($zipCodes[$index]); // the entire object
https://3v4l.org/TAXQq
Based on your code:
foreach ($zipCodes as $index => $location) { // index is a key
if ($inputZip == $location->zipcode) {
echo "Index is ".$index;
break;
}
}
var_dump($zipCodes[$index]);
I should note that it seems you are doing something wrong because you don`t suppose to store your data like this and loop through array all the time.
To get the keys of an array that is filtered due to certain parameters that must be met you could use array_keys and array_filter.
For Example
$array = [1,2,1,1,1,2,2,1,2,1];
$out = array_filter($array,function($v) {
return $v == 2;
});
print_r(array_keys($out));
Output
Array
(
[0] => 1
[1] => 5
[2] => 6
[3] => 8
)
Try the above example in PHP Sandbox
To match your actual data structure.
$json = '[{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35005,"state abbreviation": "AL","latitude": 33.606579,"longitude": -86.50649,"city": "Moody","state": "Alabama"}]';
$array = json_decode($json);
$out = array_filter($array, function($v) use ($inputZip) {
return $v->zipcode == $inputZip; // for the below output $inputZip=35004
});
print_r(array_keys($out));
Output
Array
(
[0] => 0
[1] => 1
)
Try the example in PHP Sandbox
I have a JSON i would like to target 'rank' of one of it's object(BTCUSD) in PHP, but the object arrangement is dynamic based on rank.
Below is the JSON output:
{
"tickers":[
{
"pair":"BTCUSD",
"timestamp":153900343434,
"rank":"1",
"bid":"1234.00",
"ask":"1234.00"
},
{
"pair":"BTCGBP",
"timestamp":153900343434,
"rank":"2",
"bid":"54321.00",
"ask":"54321.00"
},
{
"pair":"BTCEUR",
"timestamp":153900343434,
"rank":"3",
"bid":"54321.00",
"ask":"54321.00"
}
]
}
How i am currently getting the result i need:
$arr['RESULT'] = getJson('https://example.com/json')['tickers']['0']['rank'];
echo json_encode($arr)
The above code works, but it's not efficient because when a pair rank changes, it moves up in line and my code will only target the first inline and not BTCUSD pair.
You should search the array then. You could use array_filter.
// Grabbing the json->tickers array
$arr = getJson('https://example.com/json')['tickers'];
// Search the array
$arr = current(array_filter($arr, function($item){
return $item['pair'] == 'BTCUSD';
}));
echo json_encode($arr['rank']);
I am currently using the jQuery plotting plugin (Click), but I am having trouble fetching the data out of my database.
I am using PHP for the SQL part, which returns an array like this:
Array (
[0] => 13
[id] => 13
[1] => 320.82
[real_value_1] => 320.82
)
Now I need it in the following format in order for the flot plugin to pick it up:
[13, 320.82]
But I am having trouble figuring out how.
This is the plotting code:
$(document).ready(function(){
var url = "view_json_graph.php?type=2";
$.get(url, function(data){
console.log(data);
$.plot($("#placeholder"), data, { yaxis: { max: 100 }, xaxis: { max: 100 } });
});
});
Where the javascript var data, would be the data returned ( [13, 320.82] ).
Could anyone please give me advice on how to do it? I've also looked into JSON, but I couldn't get it to work with JSON either.
You should simplify your array first, so it would only contain the values only once:
Array (
[0] => 13
[1] => 320.82
)
After that, you could use php's implode() function, to make your array into a string, separated by commas:
$result = '[' . implode( ',', $array ) . ']';
This will be your desired format.
Dont know whether the below code helps you
<?php
$sql = "SELECT id, value FROM sample";
$query = mysqli_query($connect, $sql);
while($res = mysqli_fetch_array($query))
{
$out[] = "[".$res[0].','.$res[1]."]";
}
$comma_separated = implode(",", $out);
echo $comma_separated;
?>
With fetchAll(PDO::FETCH_ASSOC) get such array
$array =
Array
(
[0] => Array
(
[FinalCurrencyRate] => 0.000062
)
)
Need to json_encode to use in
$.post("__02.php", { 'currency': currency }, function(data, success) {
$('#currency_load').html(data.FinalCurrencyRate);
$('#currency_load0').html(data.FinalCurrencyRate0);
$('#currency_load1').html(data.FinalCurrencyRate1);//and so on
}, "json");
If simply echo json_encode($array); then does not work.
Need to convert to json format array like this:
$arr = array ('FinalCurrencyRate'=>"0.000062");
To convert to json format, wrote such code
$json_array = "{";
$flag_comma = 0;
foreach($array as $i =>$array_modified) {
if ($flag_comma == 0) {
$json_array .="'FinalCurrencyRate". $i."'=>'". $array_modified[FinalCurrencyRate]. "'";
$flag_comma = 1;
}
else {
$json_array .=", 'FinalCurrencyRate". $i."'=>'". $array_modified[FinalCurrencyRate]. "'";
}
}
$json_array .= "}";
Then echo json_encode($json_array);. And only one echo json_encode.
But does not work.
Understand that there are errors in code to convert to json format. What need to correct, please?
If I understand correctly you just want to return the first row form your array, then you just need to do this
echo json_encode($array[0]);
UPDATE
I think I see what you're trying to do now, you're trying to append the index to the FinalCurrencyRate key in each row. No need to do that, what you should do is change your javascript code to look like this:
$('#currency_load0').html(data[0].FinalCurrencyRate);
$('#currency_load1').html(data[1].FinalCurrencyRate);//and so on