php remove element from array without add key - php

I want to remove an element from an array (converted from json), but with unset, and reconvert in json, the array become indexed.
Source array:
{"rows":
[{"c":[{"v":"Date(1409052482000)"},{"v":22},{"v":22},{"v":22},{"v":null}]},
{"c":[{"v":"Date(1409052614000)"},{"v":22},{"v":22},{"v":22},{"v":null}]},
{"c":[{"v":"Date(1409052782000)"},{"v":22},{"v":22},{"v":22},{"v":null}]}
]}
Result:
{"rows":
"2":{"c":[{"v":"Date(1409052614000)"},{"v":22},{"v":22},{"v":22},{"v":null}]},
"3":{"c":[{"v":"Date(1409052782000)"},{"v":22},{"v":22},{"v":22},{"v":null}]}
}}
the problem is the "2" and "3" keys. I don't want this keys, because I use the data for google chart, and is sensible for this index key.
PHP code:
$tempdata = json_decode($jsonTempLog, TRUE);
foreach ($tempdata['rows'] as $key => $row) {
if ( $logtime < $showtime) {
unset($tempdata['rows'][$key]);
}
}
echo json_encode($tempdata);
How can I remove element from array, keep the original json syntax?

Just do this:
$tempdata["rows"] = array_values($tempdata["rows"]);
echo json_encode($tempdata);
Otherwise JSON thinks you're sending an associative array rather a numeric one

this is how i work with :
unset($infos[$i]);
$infos = array_values($infos);

maybe like this:
foreach($tempdata as $row){
$tempdata[$rows['keyfield']] = $row;
}

Related

how to replace value with spesific column with searching id on array

i have some problem with data array, how to replace spesific array column with searching in column id in array
data json array like this :
$json ='
[
{"id":1,"name":"Eko","approved":"n"},
{"id":2,"name":"Rudi","approved":"n"},
{"id":3,"name":"Yanto","approved":"n"}
]
';
ihave tried many tutorial but not spesific replace array
iwant output like this :
$json =
'
[
{"id":1,"name":"Eko","approved":"n"},
{"id":2,"name":"Rudi","approved":"y"},
{"id":3,"name":"Yanto","approved":"n"}
]
';
i apreciate with your help
defferent is "approved":"y" in json2
$array = json_decode($json);
foreach ($array as $key => $item) {
if($item->id == $your_serach_id){
$array[$key]->approved = "y";
}
}
I hope this helps.
You can tirverse the JSON object using for loop or foreach look and fetch the key value pair in the array and for getting your desired output you will need to know the value of which key you have to change so in the loop you can array[i] ->key = new_valuethis line should be thier after if condition in for loop

PHP Loop array object once, or wild card key?

I have a php array, and inside the array is a reference to another php object with a numerical value.
How can i access the elements in this array without knowing that numerical id (it could be different for each array)?
In the image below, I need to get the values inside field_collection_item like so....
$content['field_image_columns'][0]['entity']['field_collection_item'][133]['field_image']
For the first array key (0) i have done the following...
$i = 0;
while($i <= 2) {
if(isset($content['field_image_columns'][$i])) {
print '<div class="column-' . $i . '">';
foreach ($content['field_image_columns'][$i]['entity']['field_collection_item'] as $fcid => $values) {
// Print field values
}
print '</div>';
}
$i++;
}
Doing a foreach loop for a single array item seems wrong - is there a method i should be using for this use case?
You can select first item of array for example with:
Use array_shift, but it will modify source array:
$cur = array_shift($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
Get keys of array with array_keys and use first element of result as a key
$ks = array_keys($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $content['field_image_columns'][$i]['entity']['field_collection_item'][$ks[0]]['field_image'];
Use current function:
$cur = current($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
As with most programming, there are quite a few ways you could do it. If a foreach works, then it isn't wrong, but it may not be the best way.
// Get the current key from an array
$key = key($array);
If you don't need the key, then you can just get the value from the array.
// Get the current value from an array
$value = current($array);
Both of these will retrieve the first key/value from the array assuming you haven't advanced the pointer.
current, key, end, reset, next, & prev are all array functions that allow you to manipulate an array without knowing anything about the internals. http://php.net/manual/en/ref.array.php

Multidimensional array - how to get specific values from array

I have converted Excel data into Php array using toArray()..
actually my result is
My question how to get value from this Multidimensional array? and also how to i get header and value from array in separately?
you can access value, by following the path of the array. so in your case :
$yourArrayName['Worksheet'][0][0], will return SNo
Get one value:
print_r($your_array['Worksheet'][0]);
Get values with loop:
foreach ($your_array as $key => $value)
{
echo $key; // 'Worksheet'
print_r $value;
}
If you are trying to extract all the values of specific key then you should use for or foreach or while loop...
its something like
<?php
$array = YOUR ARRAY;
$c=count($array);
for ( $i=0; $i < $c; $i++)
{
echo $array[$i]['StudentName'];
}
?>
else if you want to get a specific value manually You can easily traverse to your value as
$array = YOUR ARRAY
echo $ara['Worksheet'][0]['StudentName']

Removing array index reference when using json_encode()

I have made a small application using jQuery's datepicker. I am setting unavailable dates to it from a JSON file which looks like this:
{ "dates": ["2013-12-11", "2013-12-10", "2013-12-07", "2013-12-04"] }
I would like to check if a date given is already in this list and remove it if so. My current code looks like this:
if (isset($_GET['date'])) //the date given
{
if ($_GET['roomType'] == 2)
{
$myFile = "bookedDates2.json";
$date = $_GET['date'];
if (file_exists($myFile))
{
$arr = json_decode(file_get_contents($myFile), true);
if (!in_array($date, $arr['dates']))
{
$arr['dates'][] = $_GET['date']; //adds the date into the file if it is not there already
}
else
{
foreach ($arr['dates'] as $key => $value)
{
if (in_array($date, $arr['dates']))
{
unset($arr['dates'][$key]);
array_values($arr['dates']);
}
}
}
}
$arr = json_encode($arr);
file_put_contents($myFile, $arr);
}
}
My problem here is that after I encode the array again, it looks like this:
{ "dates": ["1":"2013-12-11", "2":"2013-12-10", "3":"2013-12-07", "4":"2013-12-04"] }
Is there a way to find the date match in the JSON file and remove it, without the keys appearing after the encode?
Use array_values() for your issue:
$arr['dates'] = array_values($arr['dates']);
//..
$arr = json_encode($arr);
Why? Because you're unsetting array's key without re-ordering it. So after this the only way to keep that in JSON will be encode keys too. After applying array_values(), however, you'll get ordered keys (starting from 0) which can be encoded properly without including keys.
You are ignoring the return value of array_values in your existing attempt to reindex the array. Correct is
$arr['dates'] = array_values($arr['dates']);
The reindexing should also be moved outside the foreach loop, there is no point in reindexing multiple times.
In Laravel collections(just in case) you can do
$newArray = $collection->values()->toArray();
or
$jsonEncoded = $collection->values()->toJson();
Just pass second parameter as 'JSON_PRETTY_PRINT' to json_encode() function:
json_encode($arr, JSON_PRETTY_PRINT);
or
json_encode($arr, 128);

PHP JSON encode- Manually assign keys?

I am trying to convert a MySQL query result into JSON within an AJAX request.
My code looks like this at the moment.
$offset = empty($_GET['offset']) ? 0 : $_GET['offset'];
$numimagestodisplay = 3;
$items = array();
$allitems // This is the queryset obtained through a call to a function
foreach ($allitems as $i => &$item)
{
if (($i >= $offset) && (count($items) < $numimagestodisplay))
{
$items[$i] = $item;
}
}
$output = '{"items":'.json_encode($items).'}';
I then want to cycle through the returned results in the javascript calling the above code and need to refer to the array items by their keys (I need to alter some HTML element IDs using these values). However, the JSON is returned in the wrong format.
If I change the line
$items[$i] = $item;
to:
$items[] = $item;
Then I can refer to it by key, however the keys are obviously just 0, 1, 2, whereas I need the key to be the value defined in the loop.
How can I alter the PHP code to return the JSON in the correct format?
Any advice appreciated.
Thanks.
The problem is that arrays in Javascript (and most other languages for that matter) can't have user defined keys. You want your array to be encoded to a JSON object instead of an array (arrays in PHP with user-defined keys are in essence objects). This usually happens automatically, for arrays with non-numeric keys.
In your case, you can use the JSON_FORCE_OBJECT flag:
$output = '{"items":'.json_encode($items,JSON_FORCE_OBJECT).'}';
From the documentation:
Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}

Categories