PHP Insert array into multidimensional array is overwrite - php

I´m trying to insert arrays into other array, the problem is that when I call the array_push() method it overwrites the last one element of my array, then I just get an array with data of one array (the last one):
$users_data = [];
$resultSize = count($result);
$data = $result;
for ($i = 0; $i < $resultSize; $i++) {
$person = [
'nombre' => $result[$i]['nombre'],
'apellido' => $result[$i]['apellido'],
];
array_push($users_data, $person);
// $users_data = $person; I also have tried with this method.
};
I just receive one object with this:
Object {nombre: jane, apellido: doe}
What is going wrong?

It shud be like this,
$person['nombre'][$i] = $result[$i]['nombre'];
$person['apellido'][$i] = $result[$i]['apellido'];
^ you have missed this index.
Then no need of array_push(). you can directly assign persons to user_data

Or like this :
for ($i = 0; $i < $resultSize; $i++) {
$users_data['nombre'][] = $result[$i]['nombre'];
$users_data['apellido'][] = $result[$i]['apellido'];
};

Related

How to create empty string using for loop PHP

I'm trying to create for loop giving strings empty value. How I can do it?
for ($i = 1; $i <= 24; $i++) {
$b2_ch_v = ${'b2_g_v_'.$i}['id'];
$$b2_ch_v = '';
}
/*
result should be:
$b2_g_v_1['id'] = '';
$b2_g_v_2['id'] = '';
[...]
$b2_g_v_24['id'] = '';
*/
Don't use variables named like $x1, $x2, $x3. You almost always want to use arrays instead. In this case, you can use an indexed array of associative arrays. This is sometimes also called a two-dimensional array.
for ($i = 0; $i < 24; $i++) {
$b2_ch_v[$i] = ['id' => ''];
}
Then your first element becomes:
$b2_ch_v[0]
And its named elements can be referred to via:
$b2_ch_v[0]['id']
You're setting $b2_ch_v to the current contents of the id element of the array, not a reference to the array element. You need to refer to the array index in the assignment.
for ($i = 1; $i <= 24; $i++) {
$b2_ch_v = 'b2_g_v_'.$i;
${$b2_ch_v}['id'] = '';
}
var_dump($b2_g_v_1); // => array(1) { ["id"]=> string(0) "" }
You don't actually need the variable, you can do the calculation in the assignment:
${'b2_g_v_'.$i}['id'] = '';
But it's best to avoid variable variables in the first place, and use arrays instead as in the other answer.

Php Xml loop through addAttribute

How can I loop through addAttribute to write multiple values.
So far it looks like this:
for($i = 0; $i < 10; $i++)
{
$this->title->addAttribute('names', "'".$this->Data[$i]->names.';');
}
I get this error:
SimpleXMLElement::addAttribute(): Attribute already exists
current the xml looks like this(without the loop, with a static value name):
<button names=Tim;"/>
but I want it to look like this after the loop:
<button names=Tim;Tom;Ted"/>
how do I achieve this?
you can achieve this by first create an array with all your name, and then implode your array in your attribute
This should work
PHP
$names = [];
foreach($this->Data as $key => $value) {
$names[] = $value->names;
}
$this->title->addAttribute('names', implode(';', $names));
You do not need to use addAttribute() to add value to exist attribute. Only add new value to attribute like bottom code
for($i = 0; $i < 10; $i++)
{
$this->title['names'] .= $this->Data[$i]->names.';'
}
Check result in demo
In your code sample, you'r trying to add same attribute. Instead of it, you can create an array with names. Then you can join array elements with a glue string with implode.
$names = [];
for($i = 0; $i < 10; $i++)
{
$names[] = $this->Data[$i]->names;
}
$this->title->addAttribute('names', implode(';',$names));

Using for loop to create JSON object in PHP

I am trying to create a JSON object like this:
"results": [
{"key":"1","trackname":"graham#insideoutrenovations.com.au"},
{"key":"1","trackname":"sjwindsor#westnet.com.au"},
]
However my PHP code is creating a new object for each iteration, the json looks like this:
0: "{"key":"1","trackname":"graham#insideoutrenovations.com.au"}"
1: "{"key":"1","trackname":"sjwindsor#westnet.com.au"}"
Here is my php:
$results = array();
function json_response($trackName) {
return json_encode(array(
'key' => '1',
'trackname' => $trackName
));
}
//There is 3 reg expressions for each primary array so we need to iterate by 3, otherwise we will get 3 lots of the same email address
for ($i = 0; $i < $numMatches; $i = $i + $patternNum) {
$results[] = json_response($matches[0][$i]);
}
//$results = call_user_func_array('array_merge',$results);
echo json_encode($results);
you need to remove the first json_encode function
you can either try to create associative array or use function compact, that will do the work for you.
//There is 3 reg expressions for each primary array so we need to iterate by 3, otherwise we will get 3 lots of the same email address
for ($i = 0; $i < $numMatches; $i = $i + $patternNum) {
$results[] = $matches[0][$i]; // json_encode removed
}
echo json_encode(array('results' => $results));
// or
echo json_encode(compact('results'));
In final echo you encode in json an array already encoded.
Remove json_encode from json_response function.

PHP put several arrays in one separated by ","

I have some arrays extracted from a XML-file. These are in
$array0 = (.......)
$array1 = (.......)
...
$arrayN = (.......)
Now I need a single array with all arrays in it separated by "," as
$masterArray = array($array0,
$array1,
...
$arrayN)
I tried
for ( $i = 0; $i < N; $i++) {
$masterArray = $masterArray + $array[$i];
}
with no result. I tried array_merge but this will give one
$masterArray(......................all items of all $arrays.....)
How can I do it right?
for ( $i = 0; $i < N; $i++) {
$temp = "array".$i;
$masterArray[$i] = ${$temp};
}
Given your exact definition of what you got and what you want the routine should be:
for ( $i = 0; $i < N; $i++) $masterArray[] = ${'array'.$i};
Not much to explain here. You make a new entry in an array with $variable[] = <entry>; and you access your numbered array with a variable variable, see:
http://php.net/manual/en/language.variables.variable.php
I guess you wont to create a multi dimension array:
$masterArray = array();
$masterArray[] = $array0;
$masterArray[] = $array1;
...
$masterArray[] = $arrayN;
this will in all arrays as element of the MasterArray:
$masterArray[0=>(....),1=>(....), ...];
Then access it like this:
$arr1_key1 = $masterArray[1]['key1'] ; //$array1['key1'];
You can add specific keys if you wont:
$masterArray['arr1'] = $array1;
$arr1_key1 = $masterArray['arr1']['key1'] ; //$array1['key1']
In general read some more to get better understanding on how to work with arrays ;)

Creating arrays in for loops

I'm starting with a csv variable of column names. This is then exploded into an array, then counted and tossed into a for loop that is supposed to create another array.
Every time I run it, it goes into this endless loop that just hammers away at my browser...until it dies. :(
Here is the code..
$columns = 'id, name, phone, blood_type';
$column_array = explode(',',$columns);
$column_length = count($column_array);
//loop through the column length, create post vars and set default
for($i = 0; $i <= $column_length; $i++)
{
$array[] = $iSortCol_.$i = $column_array[$i];
//create the array iSortCol_1 => $column_array[1]...
//$array[] = 'iSortCol_'.$i = $column_array[0];
}
What I would like to get out of all this is a new array that looks like so..
$goal = array(
"iSortCol_1" => "id",
"iSortCol_2" => "name",
"iSortCol_3" => "phone",
"iSortCol_4" => "blood_type"
);
Simply change
$array[] = 'iSortCol_'.$i = $column_array[0];
to
$array['iSortCol_'.$i] = $column_array[$i];
and the <= to < in your for loop, otherwise you will display a blank array value in your end result. Because you need to go up to but not including the length of $column_array.
$array[] = 'iSortCol_'.$i = $column_array[0];
I think it's because you're assigning the value of $column_array[0] to $i AND using it as the loop index. Use another variable to do that, otherwise it just goes on and on.
EDIT Tested and pasted output
Working code, just tested it on local
$columns = 'id, name, phone, blood_type';
$column_array = explode(',',$columns);
$column_length = count($column_array);
$array = array();
for($i = 0; $i < $column_length; $i++)
{
//create the array iSortCol_1 => $column_array[1]...
$array['iSortCol_'.$i] = $column_array[$i];
}
var_dump($array);
This will output
array
'iSortCol_0' => string 'id' (length=2)
'iSortCol_1' => string ' name' (length=5)
'iSortCol_2' => string ' phone' (length=6)
'iSortCol_3' => string ' blood_type' (length=11)
Is this not what you want?
I think you meant to write:
$array['iSortCol_'.$i] = $column_array[0];

Categories