i am trying to create a customized array out of my json file. But every time i run this, nothing comes out. Why is the happening??
This is my JSON:
[{"Account":null,"Addresses":[{"Address1":"Store Kongensgade 72","City":"K\u00d8BENHAVN K","CoAddress":null,"Country":{"AttributeBag":null,"Code":"DK","Text":"Danmark"},"Type":{"AttributeBag":null,"Code":"Postal","Text":"Postadress"},"ZipCode":"1264"}]
This is my code
$json = file_get_contents("somefile");
$decarr = json_decode($json, TRUE);
print_r($decarr);
This is my current output from my decarr array:
Array ( [0] => Array ( [Account] => [Addresses] => Array ( [0] => Array ( [Address1] => Store Kongensgade 72 [City] => KØBENHAVN K [CoAddress] => [Country] => Array ( [AttributeBag] => [Code] => DK [Text] => Danmark ) [Type] => Array ( [AttributeBag] => [Code] => Postal [Text] => Postadress ) [ZipCode] => 1264 ) ) .....there is much more, but i had to stripped down.
This is my code for how to create my own array.
$count = count($decarr);
$values = array();
$update_values = array();
for ($x=0; $x < $count; $x++)
{
$newrec = $decarr[$x];
$num = $newrec['Address1']; $num = mysql_real_escape_string($num);
$desc = $newrec['City']; $desc = mysql_real_escape_string($desc);
$freq = $newrec['ZipCode']; $freq = mysql_real_escape_string($freq);
$values[] = "('".$num."', '".$desc."', '".$freq."')";
}
print_r($values);
But this is what i am getting right now.
Array ( [0] => ('', '', '') [1] => ('', '', '')....and beyond
As you can see, the selected values won't store in my values array. why is the happening?
The Address1, City, and ZipCode properties are inside an object that is an item of the Addresses array.
Change
$newrec = $decarr[$x];
To:
$newrec = $decarr[$x]['Addresses'][0];
Or if you want, you could also add all addresses:
for ($y = 0; $y < count($decarr[$x]['Addresses']); $y++) {
$newrec = $decarr[$x]['Addresses'][$y];
...
$values[] = "('".$num."', '".$desc."', '".$freq."')";
}
Related
I have the following array:
Array
(
[0] => Array
(
[0] => 2015-07-18
[1] => 22 SSH
)
[1] => Array
(
[0] => 2015-07-18
[1] => 80 HTTP
)
[2] => Array
(
[0] => 2015-07-18
[1] => 3389 Remote Desktop
)
[3] => Array
(
[0] => 2015-07-19
[1] => 3389 Remote Desktop
)
[4] => Array
(
[0] => 2015-07-19
[1] => 3389 Remote Desktop
)
)
and the following function to bring the data in the needed format/array for highcharts:
$result = array();
$result[0] = array();
$result[0][data] = array();
foreach ($stack_stats_timeline as $key => &$value) {
if(!in_array($value[0], $result[0][data], true)) array_push($result[0][data], $value[0]);
$hash = $value[1];
$result[$hash][name] = $value[1];
$result[$hash][data][$value[0]] += 1;
}
so far so good... hoever the problem is that when i do
$result = json_encode($result);
print_r($result);
I get
[{"data":["2015-07-01","2015-07-02","2015-07-03"]},{"name":"8080 Unknown","data":{"2015-07-01":4,"2015-07-02":8,"2015-07-03":5}},{"name":"8118 Unknown","data":{"2015-07-01":3}},{"name":"3389 Remote Desktop","data":{"2015-07-01":14,"2015-07-02":52,"2015-07-03":65}},{"name":"80 HTTP","data":{"2015-07-01":3,"2015-07-02":12,"2015-07-03":7}},{"name":"8228 Unknown","data":{"2015-07-01":3}}]
the problem is in data when the format is:
{"key":number,"key":number}
this should be only:
{number,number}
QUESTION: How can I remove the array keys after I sorted the occurences by date?
I would probably do something along the lines of:
$headings = $result[0]['data'];
for ($i = 0; $i < count($result[1]); $i ++) {
$data = $result[1][$i]['data'];
$newdata = array();
foreach($headings as $key)
$newdata[] = isset($data[$key]) ? $data[$key] : 0;
$result[1][$i]['data'] = $newdata;
}
Here is the raw data
Array
(
[name] => me
[tickets] => Array
(
[1] => Array
(
[equipment] => Array
(
[1] => Array
(
[name] => DVR
[received] => 10
)
[2] => Array
(
[name] => DCT
[received] => 3
)
)
)
[2] => Array
(
[equipment] => Array
(
[1] => Array
(
[name] => DVR
[received] => 4
)
[2] => Array
(
[name] => DCT
[received] => 6
)
)
)
)
)
Users have multiple tickets, but each ticket has the same item with different 'received' amounts. I would like to sum the received amount into one variable/array.
Here is a demo of how I would like to get it to work like
Array
(
[name] => me
[equipment] => Array
(
[DVR] => 14
[DCT] => 9
)
)
Here is my most recent failed attempt at building my own array from a multidimensional array.
foreach($data as $user){
$sum = [];
$sum['name'] = $user->name;
$sum['equipment'] = [];
foreach($user->tickets as $ticket){
foreach($ticket->equipments as $eqpt){
$sum['equipment'][$eqpt['name']] += $eqpt['pivot']['received'];
}
}
print_r($sum);
}
Please try the following code. There's only a single user in your $data, though, so you need to do $data = [$data]; first.
foreach ($data as $user) {
$sum = [];
$sum['name'] = $user['name'];
$sum['equipment'] = [];
foreach($user['tickets'] as $ticket){
foreach($ticket['equipment'] as $eqpt){
$sum['equipment'][$eqpt['name']] += $eqpt['received'];
}
}
print_r($sum);
}
PHP arrays are accessed with square bracket syntax
There's probably a typo in $ticket->equipments.
Try with this:
$array = $data; //$data is your array
$sum = array('name' => $array['name'], 'equipment' => array());
foreach($array['tickets'] as $row) {
for($i = 0; $i < count($row); $i++) {
foreach($row['equipment'] as $infos) {
$sum['equipment'][$infos['name']] += $infos['received'];
//print_r($infos);
}
}
}
print_r($sum);
well, after much googling and trial and error this appears to work
$sum = [];
// $data is a collection returned by Laravel
// I am converting it to an array
foreach($data->toArray() as $user){
$items = [];
foreach($user['tickets'] as $ticket){
foreach($ticket['equipments'] as $eqpt){
$name = $eqpt['name'];
if (! isset($items[$name]))
{
$items[$name] = $eqpt['received'];
} else {
$items[$name] += $eqpt['received'];
}
}
}
$sum[] = [
'name' => $user['name'],
'equipment' => $items
];
}
#tsnorri #Adrian Cid Almaguer
I have the following method:
public function selectFinal(){
$db = new Database();
for($i = 0; $i < 5; $i++){
$key_id = mt_rand(0, count($this->candidates) - 1);
$itm = $this->candidates[$key_id];
$host = $itm["host"];
$item = $itm["item"];
$db->query("insert ignore into trends (trend_id, host, item) values (?, ?, ?)", array($this->nextId, $host, $item));
array_splice($this->candidates, $key_id, -1);
print_r($this->candidates);
$this->nextId++;
}
}
For the print_r() I am getting this output:
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => IytNBm8WA1c
)
[1] => Array
(
[host] => www.youtube.com
[item] => kffacxfA7G4
)
[2] => Array
(
[host] => www.youtube.com
[item] => kXYiU_JCYtU
)
[3] => Array
(
[host] => www.youtube.com
[item] => 7AVHXe-ol-s
)
[4] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => IytNBm8WA1c
)
[1] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
The array will start with 5 or more items in it. What I would like to do is select a random item from the array and insert it into the database then remove it from the array. I want to do this 5 times to get 5 random items from the array. But for some reason it is selecting 1 then removing 3 items from the array, and I am not sure why (shown in the second section of code).
Edit: Final Working Result
public function selectFinal(){
$db = new Database();
for($i = 0; $i < 5; $i++){
$key_id = mt_rand(0, count($this->candidates) - 1);
$itm = array_values(array_merge([$this->nextId], array_splice($this->candidates, $key_id, 1)[0]));
$db->query("insert ignore into trends (trend_id, host, item) values (?, ?, ?)", $itm);
$this->nextId++;
}
}
You are more safe in splicing the element out and use that outtake. In case you made an error with that, you notice by not having correct values to store. This will make you more aware of a potential problem:
$key_id = mt_rand(0, count($this->candidates) - 1);
$itm = array_splice($this->candidates, $key_id, -1);
var_dump($itm);
See? You then can better pin-point the problem, e.g. -1 is not 1. See http://php.net/array_splice
public function selectFinal() {
$db = $this->db;
for ($i = 0; $i < 5; $i++)
{
$key_id = mt_rand(0, count($this->candidates) - 1);
$values = array_merge(
[$this->nextId], array_splice($this->candidates, $key_id, 1)
###
);
print_r($this->candidates);
$db->query(
"insert ignore into trends (trend_id, host, item) values (?, ?, ?)",
array_values($values)
);
$this->nextId++;
}
}
If you just want delete a array item of a specific key you can use -
unset($this->candidates[$key_id])
I've a series of arrays with values that goes from 1 to 5. Almost every array has missing values, some even dont have any values. My objective is to fill the missing values with 0. All those arrays are stored into a multidimensional array.
My array looks like:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[2] => Array
(
[0] => 1
[1] => 5
)
[3] => Array
(
[0] => (this array has no values)
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
etc...
)
How it should be:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => 0
)
[2] => Array
(
[0] => 1
[1] => 0
[2] => 0
[3] => 0
[4] => 5
)
[3] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
etc...
)
Any help would be appriciated!
For each of your subarrays loop through the numbers 1 to 5, and if that value exists set its key to be one less than its value:
$newarray = array();
foreach($arr as $key => $subarr) {
for ($i = 1; $i <= 5; $i++) {
if (in_array($i, $subarr)) $newarray[$key][$i - 1] = $i;
else $newarray[$key][$i - 1] = 0;
}
}
Where $newarray is your output and $arr is your input array.
You may want to note that PHP does not truly do multidimensional arrays. It only allows you to relate 2 flat arrays together which is not true multidimensionality.
This does not work and will produce results described above.
$menu[1] = "My Training"; //not $menu[1][0]
$menu[1][1] = "To Do List";
$menu[1][2] = "Catalog";
$menu[1][3] = "Self-Report";
$menu[1][4] = "Completions";
$menu[2] = "Manager";
$menu[2][1] = "Direct Reports";
$menu[2][2] = "Incompletes";
$menu[2][3] = "Completions";
$menu[3] = "Instructor";
$menu[3][1] = "My Classes";
$menu[3][2] = "Printables";
$menu[3][3] = "Qualifications";
This does work.
$menu[1] = "My Training"; //not $menu[1][0]
$submenu[1][1] = "To Do List";
$submenu[1][2] = "Catalog";
$submenu[1][3] = "Self-Report";
$submenu[1][4] = "Completions";
$menu[2] = "Manager";
$submenu[2][1] = "Direct Reports";
$submenu[2][2] = "Incompletes";
$submenu[2][3] = "Completions";
$menu[3] = "Instructor";
$submenu[3][1] = "My Classes";
$submenu[3][2] = "Printables";
$submenu[3][3] = "Qualifications";
$submenu is only related to $menu through the first key number as there are no first dimension values to $submenu.
Something like this (array_pad() won't do the trick). $myArray is your source array. Completed array is returned in $result:
$result = array();
foreach( $myArray as $subKey=>$subArray ) {
for( $i=0; $i<5; $i++ ) {
if( isset( $subArray[$i] )) {
$result[$subKey][$i] = $subArray[$i];
} else {
$result[$subKey][$i] = 0;
}
}
}
Note, we do copy of the array. You cannot fill array in-place.
It's been many years since I wrote any PHP but something like this might do the trick I guess?
for($i = 0; $i < 5; $i++)
{
if(empty($myArray[$i])
{
$myArray[$i] = 0;
}
}
i have an array like:
Array ( [0] => #!A1#DC [1] => #IMSR102.71/74.82 [2] => #HV50 [3] => #PR7/7/ [4] => #RX0 [5] => #ERN/1//0 [6] => #Q2 [7] => #!A1#DC [8] => #IMSR102.50/74.82 [9] => #HV40 [10] => #PR5/5/ [11] => #RX0 [12] => #ERN/1//1 [13] => #Q2 etc etc with hundreds o values
i get this array from a file (with the function file($filename) ) and i need to split it in many subarray.
"!A1#DC" this is the beginning of a series of values that ends with #Q2 but the number of the values between the beginning and the end is not always the same and the only 2 values that are same are the two given ("!A1#DC" for the beginning and "#Q2" for the end)
how can i get somethings like this?
Array (
[0] => Array ( [0] => #!A1#DC [1] => #IMSR102.71/74.82 [2] => #HV50 [3] => #PR7/7/ [4] => #RX0 [5] => #ERN/1//0 [6] => #Q2 )
[1] => Array (
[1] => #!A1#DC [2] => #IMSR102.50/74.82 [3] => #HV40 [4] => #PR5/5/ [5] => #RX0 [6] => #ERN/1//1 [7] => #Q2 etc etc
could you please help me?
thanks
Loop through an array. When you meet starting value, store it's index. When you meet ending value, use array_slice() to extract the part between the last pair of starting and ending values, store this part into another array.
$source = array (
'#!A1#DC',
'#IMSR102.71/74.82',
'#HV50',
'#PR7/7/',
'#RX0',
'#ERN/1//0',
'#Q2',
'#!A1#DC',
'#IMSR102.50/74.82',
'#HV40',
'#PR5/5/',
'#RX0',
'#ERN/1//1',
'#Q2',
);
$dest = array();
$startValue = '#!A1#DC';
$endValue = '#Q2';
$startIndex = 0;
foreach ( $source as $index => $value ) {
if ( $value === $startValue ) {
$startIndex = $index;
} else
if ( $value === $endValue ) {
$dest[] = array_slice($source, $startIndex, $index - $startIndex + 1);
}
}
print_r($dest);
Basically you need to loop through each element of $input, collecting those within START and END elements into a separate array:
$input = array("#!A1#DC", "A", "B", "#Q2");
$values = array();
$current = 0;
define("START", "#!A1#DC");
define("END", "#Q2");
for ($i = 0; $i < count($input); $i++) {
if ($input[$i] == END) {
// Ignore any elements after this point until we see START
$current = null;
} else if ($input[$i] == START) {
// Create a new current collection array
$current = count($values);
$values[$current] = array();
} else {
// Store the value if we are collecting
if ($current !== null) {
$values[$current][] = $input[$i];
}
}
}