create array dynamic Laravel PHP - php

i want when Foreach my Data , For Loop Add Data to Resume Array , exmaple :
Source :
foreach($getusers as $val) // 2record get data from bank But Just 1 record add to Array :(
{
$arr_data =array([
'username'=> $sec->dekey($val->user_username),
'info' => $sec->dekey($val->user_info),
'mobile' => $sec->dekey($val->user_phone),
'code' => $sec->dekey($val->user_code),
'jobside' => $val->user_jobside,
'status' => $val->user_status,
'datetime' => $val->datetime,
'userid' => $val->id,
]);
}
Export :
[{"username":"091584440004","info":"\u062d\u0627\u0646\u06cc\u0647 \u0631\u0648\u062d\u06cc","mobile":"09154479303","code":"091584440004","jobside":"EXPERT","status":"ACTIVE","datetime":"1399/08/13 - 19:26:37","userid":6}]
i want to :
[{"username":"091584440004", info ......]},[{"username":"0921538242",info ......]}, ....
Thanks .

You are overwriting your array instead of adding to it.
To initialise an array, you do:
$arr_data = []
And to append to it:
$arr_data[] = ['new' => 'entry'];
In your example:
$arr_data = [];
foreach($getusers as $val) {
$arr_data[] = [
'username'=> $sec->dekey($val->user_username),
'info' => $sec->dekey($val->user_info),
'mobile' => $sec->dekey($val->user_phone),
'code' => $sec->dekey($val->user_code),
'jobside' => $val->user_jobside,
'status' => $val->user_status,
'datetime' => $val->datetime,
'userid' => $val->id,
];
}

Related

Fetch an array of data and append all to another array?

Trial
//Get all id and name from db
foreach($fetchall as $all) {
$tobeappended = array (
'id' => $all['id'],
'name' => $all['name']
);
}
Append to
$myarray = array(
//other definition here....
'animals' => $tobeappended
);
I want to append all data from the array in foreach in the following format
[array('id' => '1','name'=>'cow'),array('id' => '2','name'=>'cat')]
Is there any way to do this
$myarray = [
'animals' => []
]
//Get all id and name from db
foreach($fetchall as $all) {
$myarray['animals'][] = [
'id' => $all['id'],
'name' => $all['name']
];
}

How to linearize a JSON and make it part of the initial array

I have an array like the following:
array(
'session_id' => 'ea29e7ae5c976794896b4c256f455dd5',
'user_identifier' => "{'user_id':87,'username':'some username','email':'someuseremail.com','first_name':'Some','last_name':'User','company':'Company'}",
'request_uri' => '/'
);
And I would like to convert it to the following:
array(
'session_id' => 'ea29e7ae5c976794896b4c256f455dd5',
'user_id' => 87,
'username' => 'some username',
'email' => 'someuseremail.com',
'first_name' => 'Some',
'last_name' => 'User',
'company' => 'Company',
'request_uri' => '/'
);
Which means I am decoding the JSON at user_identifier key and I am making part of the initial array $original and then I am removing the user_identifier key.
So far this is what I have done:
foreach ($original as $key => $log) {
$original[$key] = (array) $log;
}
foreach ($original as $key => $log) {
foreach($log as $k => $v) {
if ($k === 'user_identifier') {
$original['decoded'] = (array) json_decode($v);
}
}
}
Which is giving me an array like this one:
array(
'session_id' => 'ea29e7ae5c976794896b4c256f455dd5',
'request_uri' => '/',
'user_identifier' => "{'user_id':87,'username':'some username','email':'someuseremail.com','first_name':'Some','last_name':'User','company':'Company'}",
'decoded' => array(
'user_id' => 87,
'username' => 'some username',
'email' => 'someuseremail.com',
'first_name' => 'Some',
'last_name' => 'User',
'company' => 'Company'
)
);
As you may notice this is not even the array I am looking for and I have already one foreach loop to convert the initial result to an array - it's coming as and stdClass object - and then a nested foreach loop for decode the JSON and try to make it part of the initial array.
In such case I will need to add another loop to linearize the array. My concern is this array is just an example but the one I need to convert is a big one.
Is there any better way to achieve this?
I am using PHP 5.3.3
I would do it like this:
Extract the JSON from the original into an array. (Be sure to set the second argument of json_decode so you end up with an array instead of an object.)
$identifier = json_decode($your_array['user_identifier'], true);
merge the extracted array with the original.
$your_array = array_merge($your_array, $identifier);
Unset the now-redundant JSON
unset($your_array['user_identifier']);

php while within array

I have to populate a json with PHP.
I have this structure:
$request = array(
"api_uid" => "000000",
"api_key" => "xxxxxx",
"lista_articoli" => array(
//loop
array(
"nome" => "Acconto",
"descrizione" => "Acconto per la festa del " .$datafesta,
"prezzo_lordo" => $importo,
"cod_iva" => 0
)
// end loop
I try to use while inside array, but it's an error:
while($row = $tipologia->fetch(PDO::FETCH_ASSOC)) {
array("nome" => $row['nome'],
"descrizione" => $row['desc'],
"prezzo_lordo" => $row['prezzo_lordo'],
"cod_iva" => 0
),
}
How can i loop my data in correct way inside array?
You can't loop inside array.You need to create array and assign value to them by keys in loop.Try like below :
while ($row = $tipologia->fetch(PDO::FETCH_ASSOC)) {
$request['lista_articoli'][] = [
'nome' => $row['nome'],
'descrizione' => $row['desc'],
'prezzo_lordo'] => $row['prezzo_lordo'],
'cod_iva' => 0,
];
}

using yield to return an array of data

I never used generators in PHP. I understand the way to use it :
Foreach an array to do some tasks for each value like greping a specific line into a big file to remove some caracteres..
What I need :
I need to retrieve all bands from my dabatase. Sure I have the 'limit' argument to don't exceed the PHP's memory (there're 30 000 bands..).
I have to filters values and return a new array to the client into my REST API.
What I want to know :
Is it interesting for me to create a method into a trait called 'generator' to perform the code bellow ?
In all cases, I have to create a new array to return it into my method
$bands = Models\Bands::find($bandsParameters);
$json = [];
foreach ($bands as $band) {
$followers = $band->getFollowers();
$followersArr = [];
foreach ($followers as $follower) {
$followerImage = $follower->getImage();
$followerObj = (object)[
'id' => $follower->id,
'username' => $follower->username,
'image' => $followerImage->url,
'online' => $follower->online,
'createdOn' => $follower->createdOn,
'updatedOn' => $follower->updatedOn,
'lastLogin' => $follower->lastLogin,
];
$followersArr[] = $followerObj;
}
$info = $band->getInfo($bandInfoParameters)->getFirst();
$bandObj = (object)[
'id' => $band->id,
'name' => $band->name,
'style' => $band->styles,
'country' => $band->country,
'summary' => isset($info->summary) ? $info->summary : null,
'followers' => $followersArr,
'createdOn' => $band->createdOn,
'updatedOn' => $band->updatedOn,
'authoredBy' => $band->authoredBy,
'updatedBy' => $band->updatedBy,
];
$json[] = $bandObj;
}
return ['key' => 'bands', 'value' => $json];

php create a new array from search results of another array

My initial array is
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
I am trying to create a new array based on the search results of another array so the new array should look like this if I search for 'crafts':
$employees2 = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'brad',
'area' => 'crafts')
);
What is the simplest solution I can do get get this new result.
foreach($employees as $key => $value){
if($value['area']=='crafts'){
$employees2[] = $value;
}
}
This quite simply loops through the first array and checks the value of "area" in the internal array. If the value is equal to "crafts" you can then put that into a new array which is called $employees2. You can change crafts to whatever you want and add anything you want between the [ ] in employees2 if you wish to customise the key.
Try this:
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
$employees2 = array();
foreach ($employees as $key) {
if($key['name'] == "jack")
{
array_push($employees2,array('name'=>$key['name'],'area'=>$key['area']));
}
}
var_dump($employees2);
The array_push do all the trick ;)
Saludos.
You could simplify the syntax (but not the algorythmic complexity) by using a utility-belt library Underscore.php (http://brianhaveri.github.com/Underscore.php/)
There's a number of array-"plucking" methods that saves you the need to write loops, but under the bonnet it does much of the same as decribed in answers above.
I will assume that the possible result set can be large. In which case you would want to process the array with as little extra memory as possible. For this I suggest iterating through the array by reference and unsetting the items that do not match your criteria. Possibly less overhead than creating a new array to store the items that match your filter. Then you can check if the array is empty or not to determine if the filter returns any results. Like so:
<?php
// maybe this will be set through an option from the UI
$area_filter = 'crafts';
// fetched results
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
// filter out the items that match your filter
foreach($employees as $i => &$employee){
if($employee['area'] != $area_filter){
unset($employees[$i]);
}
}
// do something with the results
if(!empty($employees)){
print_r($employees);
} else {
echo "Sorry, your filter '$area_filter' did not match any results\n";
}
?>
Try this :
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
$employees = array_filter($employees, function($employee) {
return ($employee['area'] == 'crafts' );
});
echo "<pre>";
print_r($employees);

Categories