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);
Related
I have a collection which contains these values
'sales marketing|telemarketing',
what I'm trying to do is query/filter the items in collection but just based on the individual type so the for example value of 'telemarketing'. I have tried
$results = $data->where('Department', 'contains', $type); and also tried LIKE but because of the format with the pipe it's not picking the type/value.
This might be a dumb question but any ideas would be great!
The where-method also can handle only two Parameters. For example:
$data= collect([
['Department' => 'sales', 'price' => 200],
['Department' => 'marketing', 'price' => 100],
['Department' => 'telemarketing', 'price' => 150],
['Department' => 'marketing', 'price' => 100],
]);
$departmentName = "marketing";
$results = $data->where('Department', $departmentName);
dd($results);
Given your example:
[
"Employee" => "Some Company",
"Name" => "John Something",
"Usages" => "sales marketing|telemarketing",
"StartDate" => "1st Mar 2021",
"EndDate" => ""
]
The main issue is that the "Usage" property is a string containing multiple values, with the pipe character acting as a separator.
One solution to filter by one of those values is by mapping your original collection to transform the string in an array with the explode method and then use the filter method to filter based on the Usages you're interested in.
The resulting code might look like this:
$mappedCollection = $collection->map(function($el) {
$el['Usages'] = explode('|', $el['Usages']); // Transform the string into an array
return $el;
});
$result = $mappedCollection->filter(function($el) {
return in_array('sales marketing',$el['Usages']); // Change 'sales marketing' with the desired Usage
});
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'},
// ]
I have a probleme with a array.
In my array that has 15,000 rows, I have columns with associated names and values (sku).
I need to show all the names and make a separate on it if the sku is equal or not to the sku that is present on my product page
Exemple : array = [ 'code' => 'name1' ,
'sku' => '123456',
'code' => 'name1',
'sku' => '456789',
'code' => 'name2',
'sku' => '4565999']
etc ..........
if sku equals sku or not in my page product, i want to show the code with distinct on this .
First you need an array of arrays structure like this:
$arr = [
[ 'code' => 'name1', 'sku' => '123456' ],
[ 'code' => 'name2', 'sku' => '456789' ],
[ 'code' => 'name3', 'sku' => '4565999' ],
.
.
.
Then you can filter your array like this:
$existing_items_on_array = array_filter($arr,
function($item) use ($existing_items_on_page){
return array_search($item["sku"], $existing_items_on_page) !== false;
});
Or better (you still need to structure an array like on first solution):
I assume your SKU's are unique. Why not make them array keys?
$item_codes = [];
foreach($arr as $item){
$item_codes[$item["sku"]] = $item["code"];
}
then you would be accessing any element's code like this:
echo $item_codes[$product["sku"]]
Im retrieving data from a mysql database like following Array:
$data = [
0 => [
'id' => 1,
'Benutzer' => 'foo',
'Passwort' => '123456',
'Adresse' => [
'Strasse' => 'bla', 'Ort' => 'blubb'
],
'Kommentare' => [
0 => ['Titel' => 'bar', 'Text' => 'This is great dude!'],
1 => ['Titel' => 'baz', 'Text' => 'Wow, awesome!']
]
],
]
Data like this shall be stored in a mongo database and therefore i want to replace the keynames with translated strings that come from a config- or languagefile ('Benutzer' -> 'username').
Do i really have to iterate over the array and replace the keys or is the a better way to achieve that?
If you don't want to iterate over the array then you can change the column name in the query itself using select() function.
Considering your model name is Client then your query will be:
Client::select('Benutzer as username', '...') // you can use `trnas()` function here also
->get()
i am sending an ordered json_encode list of some MySQL tables, from php, but when i retrieve it with jquery it is not in order any more? everything works fine and in order on the php side. it's the client side that i'm having trouble with. i think the problem is that i'm sending a multidimensional array from php as json. what would be the most efficient solution? also why has the order changed when retrieved by jQuery.
PHP CODE:
$user_data = array();
while($row = mysql_fetch_array($retval, MYSQL_ASSOC){
$user_id = $row['user_id'];
if(!isset($user_data[$user_id]){
$user_data[$user_id] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'dept' => $row['dept'],
'quals' => array()
);
}
$quals = array(
'qual_cat' => $row['qual_cat'],
'qual' => $row['qual'],
'count' => $row['count']
)
$user_data[$user_id]['quals'][] = $quals;
}
echo json_encode($user_data);
jQuery:
$.post('page.php', function(post){
$.each(post, function(i,data){
alert(data.first_name+' '+data.last_name+' - '+data.dept);
});
});
PHP VAR_DUMP:
array
10 =>
array
'first_name' => string 'David' (length=5)
'last_name' => string 'Dan' (length=3)
'dept' => string 'web' (length=3)
'count' => string '5' (length=1)
'quals' =>
array
0 =>
array
...
1 =>
array
...
2 =>
array
...
3 =>
array
...
4 =>
array
...
In php, array is by default associative, so that's why you have this behavior as associative array order is not guaranteed (as per explanation in the link given by benedict_w).
To overcome this, you could try the following:
echo json_encode(array_values($user_data));
This will effectively turn your json from
["10":{prop1:val1, prop2:val2}, "25":{prop1:val1, prop2:val2}]
into
[{prop1:val1, prop2:val2}, {prop1:val1, prop2:val2}]
If you need to keep track of the id, put it inside your user_data in your php:
if(!isset($user_data[$user_id]){
$user_data[$user_id] = array(
'id' => $user_id,
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'dept' => $row['dept'],
'quals' => array()
);
}