How to convert strings to 2D array in php? - php

I have 2 strings which returns me the url and status from a curl call. I want to combine these two strings and create an array so that I can convert back to json object to fetch it in the twig.
I have tried using the explode() and the array() function.
$url =
"'http://www.testsite.com','http://www.google.org','http://www.fb.net'";
$status = 200,300,404;
var testArray = array($url,$status);
I want to make my array look like :
testArray[0][$url] = http://www.testsite.com and
testArray[0][status] = 200

Explode both strings, then loop over them and push an associative array with the values onto the result array.
$testArray = [];
$url_array = explode(',', $url);
$status_array = explode(',', $status);
foreach ($url_array as $i => $u) {
$u = trim($u, "'"); // remove surrounding quotes
$s = $status[$i];
$testArray[] = ['url' => $u, 'status' => $s];
}

Related

Convert a string structured as a Multidimensional Array to array

I have this string:
array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));
Stored in $_POST['data']
The string Im receiving is via.load` function where the structure of the string is constructed like so.
I would like to convert it to a multidimensional array via php so I can loop through it easily
So far I`ve reached a workaround by modifying both the string and the method.
Now my string looks like this :
1,name1,1,0,|2,name2,0,1,|3,name3,0,1,|4,name4,1,1,|5,name5,1,0,|
And the method is this
$data2 = $_POST['data2']; /// get data
$data2 = substr_replace($data2 ,"", -2); // eliminate ,|
$data2 = $data2."|"; // add |
$one=explode("|",$data2); // create multidimensional array
$array = array();
foreach ($one as $item){
$array[] = explode(",",$item);
}
I can keep this solution but I would like to know if there is another way of doing it as first requested
There is a better and simple way. You just need to use a foreach loop inside foreach loop.
$data = array(
array('1','name1','1','0'),
array('2','name2','0','1'),
array('3','name3','0','1'),
array('4','name4','1','1'),
array('5','name5','1','0')
);
foreach( $data as $d ) {
foreach( $d as $value ) {
echo $value;
echo '<br />';
}
}
You can check the online Demo
To parse your original string you can use eval()
$string = 'array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));';
eval('$array = '.$string);
But eval can/should be disabled on the server, because it comes with security issues.
What i would do is to use JSON, where you would POST the json encoding it with:
json_ecnode( $my_array );
and then decoding it:
$array = json_decode( $_POST['data'], true );

Adding Curly Braces on Array of String PHP

Im looking for the way to add curly braces {} on my Array of string :
print_r(json_encode($temp));
temp = [{"Red":1,"Blue":2,"Green":2}]
Im creating that values with :
$query_final = (my query);
$query = $this->db->query($query_final)->result_array();
$res = array_count_values(array_column($query, 'status'));
array_push($temp, $res);
print_r(json_encode($temp));
become:
print_r(json_encode($temp));
temp = [{"Red": "1"},{"Idle":"2"},{"Overload":"2"}]
So far i've tried to use implode :
$temp = implode(",", $temp);
print_r(json_encode($temp));
but it just giving the error, is there any way to do the right thing ?
array_count_values() returns a list of the values and the number of times they occur, so just using array_push() will add this entire array as 1 item and give you the results your getting.
Instead, you can add the results one at a time to the $temp array and get the results your after...
$temp = [];
$res = array_count_values(array_column($query, 'status'));
foreach ( $res as $key=>$item ) {
$temp[] = [$key => $item];
}
print_r(json_encode($temp));
Decode your json with json_decode($temp, true);
You can use json_encode on an array to get a JSON. Like so:
$temp = ['Red' => 1,
'Blue' => 2,
'Green' => 2
];
print_r(json_encode($temp)); // {"Red":1,"Blue":2,"Green":2}

Checking a value if in array

How do i correct my code ..i would like to check a value if is in array
$years[] = ''.$myyear.'';
$years_array = "array('" . implode( "','", $years) . "');";
if (in_array("2017", $years_array))
{
//do this
}
else
{
//do this
}
Your in_array with if clause looks fine, but year_array is wrong (which is string not array)
You can define year_array simply like below
$years_array = array(2015,2016,2017,2018);
OR
// Define array
$years_array = array();
// Add elements to array
$years_array[] = 2015;
$years_array[] = 2016;
$years_array[] = 2017;
In case if you have list of years as string separated by comma, then you can create array using explode() function like below
// this is string
$year_string = '2015,2016,2017,2018';
// this is array
$year_array = explode(',', $year_string);
// print string
print $year_string.PHP_EOL;
// print the contents of array
print_r($year_array);
meanwhile you can read more about arrays from here

Explode and make array for every value

I've tried to make this:
phones:[{"numbers":12345},{"numbers":67890}]
How can I achieve that from an explode?
$phones = "123456;7890
$phones = explode(';', $phones);
I've tried using foreach like this:
foreach($phones as $phone){
$array["numbers"] = $phone;
}
But it keep replacing the first key. and yes i read that PHP array can't have the same key on an array.
The problem is that you're setting the 'numbers' key in the array on each iteration. Instead, you want the result to be an array where every element is an associative array where the key is 'numbers' and the value is a number:
$phones = "123456;7890";
$exploded = explode(';', $phones);
$result = array();
foreach ($exploded as $elem) {
$result[] = array('numbers' => $elem);
}

Pushing an Array element into an existing multidimensional array in codeigniter

I have a query in codeigniter like this
$query_tutors = $this->db->get_where("tutor_info", array('tutor_id' => $tutor_id));
I have also other array elements that I want to pass in the query which depends on some conditions.
So how do I push other multidimensional array elements to the existing array so I can pass the variable as a whole in the query?
array_push is not working in this case.
$array = array();
$array = array("tutor_id" => $tutor_id);
$array = array("online" => $online); // want to merge this to the 1st array.
$query_tutors = $this->db->get_where("tutor_info", $array);
First you're doing it wrong.
$array = array();
$array = array("tutor_id" => $tutor_id);
You're recreating the array again, which will delete it from the memory. Either you have to use
$array['tutor_id'] = $tutor_id;
$array["online"] = $online;
or
$array = array('tutor_id' => $tutor_id, 'online' => $online);
or if you want to merge two arrays
$array = array_merge(array('tutor_id' => $tutor_id), array('tutor_id' => $tutor_id));
Your initial code
$array = [];
$array = ["tutor_id" => $tutor_id];
Now, if you want to add conditional merge, simply follow,
if($condition)
{
$array = array_merge($array, ["online" => $online]);
}
If $condition == true You final array will be,
$array = ['tutor_id' => $tutor_id, 'online' => $online];
You are almost there, just need to read a little bit more about associative arrays.
Solution:
$array = array();
$array["tutor_id"] = $tutor_id;
$array["online"] = $online;
$query_tutors = $this->db->get_where("tutor_info", $array);
This way your $array will have all indexes which you want.
You can do something like this:
$array = array();
if (!empty($tutor_id))
{
$array["tutor_id"] = $tutor_id;
}
if (!empty($online))
{
$array["online"] = $online;
}
$query_tutors = $this->db->get_where("tutor_info", $array);

Categories