Concatenate arrays to use in json encoding - php

I have an array $options:
$options = ('value' => '87', 'text' => 'Accessorize', 'image' =>'accessorize.ico'),('value' => '35', 'text' => 'Adams Kids', 'image' =>'AdamsKids.ico');
After using json_encode produce an output string like this:
[{"value":"87","text":"Accessorize","image":"accessorize.ico"},{"value":"35","text":"Adams Kids","image":"AdamsKids.ico"}]
but what I want is to add an entry at the beginning to have:
[{"value":"0","text":"- Select Shop -","image":""},{"value":"87","text":"Accessorize","image":"accessorize.ico"},{"value":"35","text":"Adams Kids","image":"AdamsKids.ico"}]
I created the following array:
$first = array('value' => '0', 'text' => '- Select Shop -', 'image' =>'');
and I used the following cancatenation methods:
$options2 = array_merge($first, $options);
$options2 = $first + $options;
but both produce the following:
{"value":"0","text":"- Select Shop -","image":"","0":{"value":"87","text":"Accessorize","image":"accessorize.ico"},"1":{"value":"35","text":"Adams Kids","image":"AdamsKids.ico"},"2":{"value":"92","text":"Alex and Alexa","image":"alexandalexa.ico"}}
which contains these incremental numerical values (the actual array contains about 200 items).
How can I add the first line to get the desired uotput, i.e.:
[{"value":"0","text":"- Select Shop -","image":""},{"value":"87","text":"Accessorize","image":"accessorize.ico"},{"value":"35","text":"Adams Kids","image":"AdamsKids.ico"}]

$options2 = array_unshift($options,$first);
array_unshift()

Related

Add PHP string value to JSON array

I got this:
$arr = json_decode($arr, TRUE);
while($row){
// $arr[] = ['id' => '8', 'name' => 'mickey'];
$test = $row->TCI_LIBELLE;
$arr[] = ['id' => $row->TCI_ID, 'name' => $row->TCI_LIBELLE];
$i +=1;
$row = $reqCentreInteret->fetch(PDO::FETCH_OBJ);
$json = json_encode($arr);
If you don't understand I'm trying to put values I get from a Select SQL query into a JSON array.
The problem is that it does't work like I want.
Indeed it works with my id because in my database it's an int value, but it does't work for the name because it is a varchar value
This is what i want to obtain :
[{"id":"8","name":"mickey"},{"id":"8","name":"mickey"}]
And here 'mickey' will be replaced by the value of my php string that will be initialized by my sql query
I already tried to solve my problem using
'name' => '" .$row->TCI_LIBELLE."'
But it does't work
How can I pass string value (or other type) to my JSON array?
I'm using PHP and JSON to send value from MySQL to an Android app.
arr[] = adds a new row to the array, i.e. a new top-level element.
You probably want to add your data to the existing element
Let's say your arr initially is something like
[ 'property1' => 'value1',
'property2' => 'value2'
...]
when you're doing
arr[] = ['id'=> 8,'name' => 'mickey']
your array will now contain 2 top level elements and look like
[[ 'property1' => 'value1',
'property2' => 'value2'
...
],
[ 'id' => 8,
'name' => 'mickey'
]
]
you may want to do this instead
arr['id'] = $row->TCI_ID;
arr['name'] = $row->TCI_LIBELLE;
then your arr will look like this:
[ 'property1' => 'value1',
'property2' => 'value2'
'id' => 8
'name' => 'mickey'
...
]
Finally this is what is had to do
$stmt = $db->query("SELECT TCI_ID AS id, TCI_LIBELLE AS nom FROM
OSO_DEV.T_CENTRE_INTERET");
echo json_encode($stmt->fetchAll(PDO:: FETCH_ASSOC),JSON_UNESCAPED_UNICODE);

Create Main Array that includes multiple child array

How Can I Create a main array that includes multiple child array And be in the form of Jason and I want to add the child Array to main array in the Loop
MainArray=[
array1=[{fname:asdada,lastname:sdsadasda}];
array2=[{fname:asdada,lastname:sdsadasda}];
array3=[{fname:asdada,lastname:sdsadasda}];
];
echo MainArray[1]->fname;
Please see the following pseudo code below:
pseudo code
You should really look into a basic php tutorial.
This is how you do it.
$mainArray = [
'array1' => ['fname' => 'asdada', 'lastname' => 'sdsadasda'],
'array2' => ['fname' => 'asdada', 'lastname' => 'sdsadasda'],
'array3' => ['fname' => 'asdada', 'lastname' => 'sdsadasda']
];
echo $mainArray['array1']['fname'];
Or use the long notation if you have an older version of php or want backwards compatibility.
$mainArray = array(
'array1' => array('fname' => 'foo', 'lastname' => 'bar'),
'array2' => array('fname' => 'lorem', 'lastname' => 'ipsum'),
'array3' => array('fname' => 'test', 'lastname' => 'example')
);
echo $mainArray['array1']['fname'];
Explanation:
The php variable sigil is $. This means that in order to access a variable or assign something to a variable, you use $mainArray. See more on variables in the documentation.
The php array can be used in two different notations. Either array(...) or, from php 5.4 upwards, [...]. Other than the opening and closing parts, they are identical. You don't use : or = to assign individual values inside an array declaration. For this you use the => operator. Each element in an array is separated by a comma (,).
E.g.
$mainArray = array(
'A' => 1,
'B' => 2
];
Arrays in Php can be either associative or numerical. What you probably want is that your outer array is numerical, meaning you can access it using $mainArray[1], and your inner array is associative. For numerical arrays, you don't specify a key yourself, so there is no need for the =>.
$mainArray = array(
array(),
array(),
array()
);
And with associative sub arrays this becomes:
$mainArray = array(
array('firstname' => 'foo', 'lastname' => 'bar'),
array('firstname' => 'test', 'lastname' => 'example'),
array('firstname' => 'lorem', 'lastname' => 'ipsum')
);
In order to access the firstname key of the first child array in this multilevel array structure, you do:
$mainArray[0]['firstname']
E.g. (if you want to echo it to the standard output)
echo $mainArray[0]['firstname'];
Please note that numerical arrays in php start counting on 0, as in most other programming languages. And please note that the key in the associative array is a string, and as such must be surrounded with either ' or ".
I can recommend you search for a php beginner's tutorial and try to write and execute the examples yourself, to get a better grasp of php. If you need somewhere to run your php examples, I can recommend you try an online php environment such as PHPFiddle.
Update on adding values:
You can add more key=>value pairs to an associative array or add more values to a numerical array afterwards in much the same way as you would access or assign to it.
First, let's add a value to a numerical array. You do this by adding [] to the end of your variable when assigning. This means that what you assign will be added as a new numerical value to the end of your array.
$numericalArray = array(
7,
8,
6,
12,
'B'
);
$numericalArray[] = 'C';
// Results in the array: array(7, 8, 6, 12, 'B', 'C')
And in order to add a new key => value pair to an associative array, you just add it using the new key, e.g.
$assoc = array(
'firstname' => 'Testy',
'lastname' => 'McTestface'
);
$assoc['middlename'] => 'Tester';
So to add a new fname-lastname pair to the mainArray, you would do:
$mainArray = array(
array('fname' => 'foo', 'lastname' => 'bar'),
array('fname' => 'test', 'lastname' => 'example'),
array('fname' => 'lorem', 'lastname' => 'ipsum')
);
$mainArray[] = array('fname' => 'new name', 'lastname' => 'new last name');
If you want to do this in a loop, you will use the for, foreach, while or do while structures.
E.g.
$mainArray = array(
array('fname' => 'foo', 'lastname' => 'bar'),
array('fname' => 'test', 'lastname' => 'example'),
array('fname' => 'lorem', 'lastname' => 'ipsum')
);
for ($i = 0; $i < 3; ++$i) {
$mainArray[] = array('fname' => 'new name ' . $i, 'lastname' => 'new last name ' . $i);
}
echo json_encode($mainArray, JSON_PRETTY_PRINT|JSON_UNESPACED_UNICODE|JSON_UNESCAPED_SLASHES), PHP_EOL;
// [
// {'fname': 'foo', 'lastname': 'bar'},
// {'fname': 'test', 'lastname': 'example'},
// {'fname': 'lorem', 'lastname': 'ipsum'},
// {'fname': 'new name 0', 'lastname': 'new last name 0'},
// {'fname': 'new name 1', 'lastname': 'new last name 1'},
// {'fname': 'new name 2', 'lastname': 'new last name 2'},
// ]

Combine arrays with a common value into a new array

I am working on a project and I am stuck on this my question is I have one array which is like below
$arr1 = array(
array
(
'id' => '1',
'city' => 'A.bad',
),
array
(
'id' => '2',
'city' => 'Pune',
),
array
(
'id' => '1',
'city' => 'Mumbai',
)
);
and I have to compare the this by id and I want the output like below.
$result = array(
array(
'id'='1',
'city'='A.bad','Mumbai'
),
array(
'id'='2',
'city'='Pune'
)
);
if we have same id as in the first one is A.bad so it will take it and in the third one it has id 1 and city as mumbai so it will combine as id 1 and city as a.bad,mumbai and other records are filtered in same manner.
Loop through the array and generate a new array depending on the id.You can try this -
$new = array();
foreach($arr1 as $array) {
$new[$array['id']]['id']= $array['id'];
// check if the city value set for that id
// if set the concatenate else set with the city name
$new[$array['id']]['city']= (isset( $new[$array['id']]['city'])) ? ($new[$array['id']]['city'] . ',' . $array['city']) : $array['city'];
}
Fiddle
If you are getting that data from database the you can group them in the query also.

need to array display in specific format in php

Capture the 'p_data' values into key/pairs and return as table
i try to array display in table format please help me.
$diskspace = array (
'S' =>
array ('DISK-FREE' =>
array (
'name' => 'S',
'desc' => 'FREE',
'p_data' => '\'C:\\ %\'=19%;99;95 \'C:\\\'=17B;3;1073741824;0;21476171776 \'D:\\ %\'=63%;99;99 \'D:\\\'=80B;3;1073741824;0;214753800192 \'E:\\ %\'=91%;99;98 \'E:\\\'=58B;3;1073741824;0;64420311040',),
),
'T' =>
array ('DISK-FREE' =>
array ('name' => 'T',
'desc' => 'FREE',
'p_data' => '\'C:\\ %\'=11%;99;95 \'C:\\\'=15B;3;1073741824;0;21476171776 \'D:\\ %\'=18%;99;99 \'D:\\\'=62B;3;1073741824;0;214753800192',),
),
'P' =>
array ('DISK-USED' =>
array ('name' => 'P',
'desc' => 'FREE',
'p_data' => '\'G:\\ %\'=19%;99;95 \'G:\\\'=92B;3;1073741824;0;21476171776',),
),
);
HTML Output
name, diskname, disk-size, disk-percentage
S, C:\, 17B, 19%
S, D:\, 80B, 63%
S, E:\, 58B, 91%
T, C:\, 15B, 11%
T, D:\, 62B, 18%
P, G:\, 92B, 19%
Use this code to extract All xxB and xx% data and try to display them drom array, make sure you try this for S , T , ... or other data in array
function Disk2Array($Name , $array) {
return $array[$Name]['DISK-FREE']['p_data'];
}
$precent = '/[0-9][0-9]\%/';
$size = '/[0-9][0-9][B]/';
preg_match_all($size , Disk2Array('S' , $diskspace) , $match);
print_r($match);
preg_match_all($precent , Disk2Array('S' , $diskspace) , $match);
print_r($match);
You have not specified what you wanted to put into the specific attributes as values and I am reluctant to guess it, so I will assume that you have a function which handles a passed p_data and returns the array you need to have.
function handlePValue($p_value) {
//your code here to return the desired value
}
$p_dataValues = array();
foreach ($diskspace as $element) {
$p_dataValues[] = handlePValue($element["p_data"]);
}

passing query fields n rows to array

I'm trying to fetch all rows to an array variable
array that i want is like this
$data1 = array('fields'=>array(
array(
'id' => 1,
'nama_file' => "sunset.jpg",
'judul' => "Sunset",
'isi' => "Matahari terbenam indah sekali",
),
array(
'id' => 2,
'nama_file' => "water_lilies.jpg",
'judul' => "Bunga Lilly",
'isi' => "Bunga lilly air sangat indah",
),)
And I've done this:
$q = $this->db->query('select id, nama_file, judul, isi from tfoto where dihapus ="T" ');
$data1=array('fields');
foreach($q->result() as $row) {
$data1['fields']=array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
}
test output:
<?php
foreach($fields as $field){
echo $field['nama_file'];
.
.
.
};?>
and I got Message: Illegal string offset 'nama_file';'judul'; etc.
I am a newbie to MySQL/PHP, so forgive me if this is a very basic question. I tried looking all over but I could not find an answer to it.
This line:
$data1['fields']=array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
Should be:
$data1['fields'][] = array('id'=>$row->id,'nama_file'=>$row->nama_file,'judul'=>$row->judul, 'isi'=>$row->isi);
Because you have to append new arrays to $data1 and not replacing it.

Categories