Filling the array value if it is missing in the assoc array?
I have an :
$A= array("A1"=>array("a"=>1,"b"=>2,"d"=>3),
"A2"=>array("a"=>4,"b"=>3,"c"=>2,"d"=>1)
);
base on the A["A2"] size is bigger than A["A1"]
I want got the new $A look like this
$A= array("A1"=>array("a"=>1,"b"=>2,"c"=>"0.00","d"=>3),
"A2"=>array("a"=>4,"b"=>3,"c"=>2,"d"=>1)
);
i'd do it this way:
if (count($A['A2']) > count($A['A1'])){
foreach($A['A2'] as $key => $value){
if (!array_key_exists($key, $A['A1'])){
$A['A1'][$key] = '0.00';
}
}
}
Related
This is my code`
$a =json_decode($user->name, true);
And I need to loop $a, but I'm getting
"Invalid Argument supplied for foreach"
while executing
`
you can loop in array and i think the result of this $a =json_decode($user->name, true);
is string
Based on what you've posted in the other answer and the comment to me, you need to change your loop to this:
foreach($a[0] as $akey => $aloop) { array_push($array, $aloop->email)); }
Notice the change from $a to $a[0]
You should describe to us how your JSON String look like.
Maybe you can try this code below :
$user= '[{"name":"Jonathan Suh","email":"jonathan.suh#gmail.com"},
{"name":"William Phil","email":"will.phil#gmail.com"},
{"name":"Allison Kin","email":"allison.kin#gmail.com"}]';
// Replace with your own JSON
$a = json_decode($user, true); // Array
// Create empty array to hold query results
$array = [];
// Begin loop ( foreach )
foreach ($a as $akey => $aloop) {
array_push($array, ['name' => $aloop["name"], 'email' => $aloop["email"]]);
}
// Encode your array result from Loop Process to JSON
// You can change whatever you want to do from your Result Loop
$jsonENC = json_encode($array);
// You know what is this...
echo $jsonENC;
how can i update data from array multidimension in php, but its from key and value array like this :
$array1=array(
array('data1'=>'name','data2'=>'age'),
array('data1'=>'names','data2'=>'ages')
);
how can i get result from array like this
UPDATE tablename SET data1='name',data2='age' WHERE 1;
i tried this but the result not like above
foreach($array1 as $arrays) {
foreach($arrays as $key => $value){
echo $key."="."'".$value."'".", ";
}
}
result:
data1='name',data2='age', data1='name',data2='age'
i want result like this :
data1='name',data2='age'
i hope can help me.
Because you only want to get content of first array, you should loop through first array only
foreach($array1[0] as $key => $value){
echo $key."="."'".$value."'".", ";
}
// data1='name', data2='age',
I have an array of dictionnaries like:
$arr = array(
array(
'id' => '1',
'name' => 'machin',
),
array(
'id' => '2',
'name' => 'chouette',
),
);
How can I find the name of the array containing the id 2 (chouette) ?
Am I forced to reindex the array ?
Thank you all, aparently I'm forced to loop through the array (what I wanted to avoid), I thought that it were some lookup fonctions like Python. So I think I'll reindex with id.
Just find the index of array that contains the id you want to find.
SO has enough questions and answers on this topic available.
Assuming you have a big array with lots of data in your real application, it might be too slow (for your taste). In this case, you indeed need to modify the structure of your arrays, so you can look it up faster, e.g. by using the id as an index for the name (if you are only interested in the name).
As a for loop would be the best way to do this, I would suggest changing you array so that the id is the arrays index. For example:
$arr = array(
1 => 'machin',
2 => 'chouette',
);
This way you could just get the name for calling $arr[2]. No looping and keeping your program running in linear time.
$name;
foreach ($arr as $value){
if ( $value['id'] == 2 ){
$name = $value['name'];
break;
}
}
I would say that it might be very helpful to reindex the information. If the ID is unique try something like this:
$newarr = array();
for($i = 0;$i < count($arr);$i++){ $newarr[$arr[$i]['id']] = $arr[$i]['name']; }
The result would be:
$newarr = array('1'=>'machin','2'=>'chouette');
Then you can go trough the array with "foreach" like this:
foreach($newarr as $key => $value){
if($value == "machin"){
return $key;
}
}
But of course the same would work with your old array:
foreach($arr as $item){
if($item['name'] == "machin"){
return $item['id'];
}
}
It depends on what you are planning to do with the array ;-)
array_key_exist() is the function to check for keys. foreach will help you get down in the multidimensional array. This function will help you get the name element of an array and let you specify a different id value.
function findKey($bigArray, $idxVal) {
foreach($bigArray as $array) {
if(array_key_exists('id', $array) && $array['id'] == $idxVal) {
return $array['name'];
}
}
return false;
}
//Supply your array for $arr
print(findKey($arr, '2')); //"chouette"
It's a bit crude, but this would get you the name...
$name = false;
foreach($arr as $v) {
if($v['id'] == '2') {
$name = $v['name'];
break;
}
}
echo $name;
So no, you are not forced to reindex the array, but it would make things easier.
Im trying to add a key=>value to a existing array with a specific value.
Im basically looping through a associative array and i want to add a key=>value foreach array that has a specific id:
ex:
[0] => Array
(
[id] => 1
[blah] => value2
)
[1] => Array
(
[id] => 1
[blah] => value2
)
I want to do it so that while
foreach ($array as $arr) {
while $arr['id']==$some_id {
$array['new_key'] .=$some value
then do a array_push
}
}
so $some_value is going to be associated with the specific id.
The while loop doesn't make sense since keys are unique in an associative array. Also, are you sure you want to modify the array while you are looping through it? That may cause problems. Try this:
$tmp = new array();
foreach ($array as $arr) {
if($array['id']==$some_id) {
$tmp['new_key'] = $some_value;
}
}
array_merge($array,$tmp);
A more efficient way is this:
if(in_array($some_id,$array){
$array['new_key'] = $some_value;
}
or if its a key in the array you want to match and not the value...
if(array_key_exists($some_id,$array){
$array['new_key'] = $some_value;
}
When you use:
foreach($array as $arr){
...
}
... the $arr variable is a local copy that is only scoped to that foreach. Anything you add to it will not affect the $array variable. However, if you call $arr by reference:
foreach($array as &$arr){ // notice the &
...
}
... now if you add a new key to that array it will affect the $array through which you are looping.
I hope I understood your question correctly.
If i understood you correctly, this will be the solution:
foreach ($array as $arr) {
if ($arr['id'] == $some_id) {
$arr[] = $some value;
// or: $arr['key'] but when 'key' already exists it will be overwritten
}
}
How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
//create a new variable called $elem1 (or $other or $elemother, etc.)
//and assign it some default value 1
}
foreach ($myarray as $name) {
$$name = 1;
}
This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.
goreSplatter's method works and you should use that if you really need it, but here's an alternative just for the kicks:
extract(array_flip($myarray));
This will create variables that initially will store an integer value, corresponding to the key in the original array. Because of this you can do something wacky like this:
echo $myarray[$other]; // outputs 'other'
echo $myarray[$lastelement]; // outputs 'lastelement'
Wildly useful.
Something like this should do the trick
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
$myVars[$arr] = 1;
}
Extract ( $myVars );
What we do here is create a new array with the same key names and a value of 1, then we use the extract() function that "converts" array elements into "regular" variables (key becomes the name of the variable, the value becomes the value).
Use array_keys($array)
i.e.
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
$namesOfKeys = array_keys($myVars );
foreach ($namesOfKeys as $singleKeyName) {
$myarray[$singleKeyName] = 1;
}
http://www.php.net/manual/en/function.array-keys.php